Home > other >  Problem to replace a strange string need some advise
Problem to replace a strange string need some advise

Time:08-09

I was transforming my object data to float and int and I found this error:

ValueError: invalid literal for int() with base 10: '[24]'

from what I understand the [] are like strings and I'm having trouble removing them and leaving just the number, how do I do that? I tried to replace but when I put '[]' as a character to replace, it understands as a list, I want to remove [] to leave only the number,

CodePudding user response:

You can try .str.strip

df['out'] = df['col'].str.strip('[]')
print(df)

    col out
0  [23]  23
1  [23]  23
2  [23]  23

CodePudding user response:

If you're certain that you have exactly one [ at the start and one ] at the end, you can just slice the string to remove the first and last character:

>>> foo = '[24]'
>>> int(foo[1:-1])
24

Another option is the str.strip() function, which is usually used to strip whitespace, but you can tell it to remove other characters, like brackets:

>>> int(foo.strip('[]'))
24

CodePudding user response:

Simple use eval() function. It will evaluate the expression turning string into list then use slicing to get desired result like this.

data = eval('[24]')
int(data[0]) 

CodePudding user response:

foo = '[24]'
bar = foo[foo.find("[") 1:foo.find("]")]
print(int(bar))
  • Related