Home > Software engineering >  How do I make '"1"' into an integer?
How do I make '"1"' into an integer?

Time:07-02

In this case, p is a list that is [' /gene="1"',' /gene="2"',…]

ValueError                                Traceback (most recent call last)
<ipython-input-96-93a440c16f3d> in <module>()
     38 
     39 for i in p:
---> 40   Gene.append(int(i.replace("  /gene=","")))

ValueError: invalid literal for int() with base 10: '"1"'

You see, a simple int() doesn't work. It can't turn '"1"' into 1. Is there a way to turn '"1"' into 1? What is it?

CodePudding user response:

I’d use strip() to trim those down like:

p=['  /gene="1"','  /gene="2"']
Gene=[]
for i in p:
  Gene.append(int(i.replace("  /gene=","").strip("\" ")))

or even:

p=['  /gene="1"','  /gene="2"']
Gene=[]
for i in p:
  Gene.append(int(i.strip("/gen=\" ")))

or if you don't want to deal with the left side of the equals sign use partition:

p=['  /gene="1"','  /gene="2"']
Gene=[]
for s in p:
    _, _, value = s.partition('=')
    Gene.append(value.strip("\" "))

CodePudding user response:

You can replace the quotes also:

Gene.append(int(i.replace("  /gene=","").replace('"','').replace("'",'')))

However, I would recommend looking at RegEx for handling parsing scenarios like this one.

CodePudding user response:

You have to remove the quotes around the number as well.

Gene.append(int(i.replace('  /gene=', '').replace('"', ''))
  • Related