Python: How To Remove [' And ']?
I want to remove [' from start and '] characters from the end of a string. This is my text: '['45453656565']' I need to have this text: '45453656565' I've tried to use str.replac
Solution 1:
You need to strip your text by passing the unwanted characters to str.strip()
method:
>>>s = "['45453656565']">>>>>>s.strip("[']")
'45453656565'
Or if you want to convert it to integer you can simply pass the striped result to int
function:
>>>try:... val = int(s.strip("[']"))...except ValueError:...print("Invalid string")...>>>val
45453656565
Solution 2:
Solution 3:
You could loop over the character filtering if the element is a digit:
>>>number_array = "['34325235235']">>>int(''.join(c for c in number_array if c.isdigit()))
34325235235
This solution works even for both "['34325235235']"
and '["34325235235"]'
and whatever other combination of number and characters.
You also can import a package and use a regular expresion to get it:
>>>import re>>>theString = "['34325235235']">>>int(re.sub(r'\D', '', theString)) # Optionally parse to int
Solution 4:
Instead of hacking your data by stripping brackets, you should edit the script that created it to print out just the numbers. E.g., instead of lazily doing
output.write(str(mylist))
you can write
for elt in mylist:
output.write(elt + "\n")
Then when you read your data back in, it'll contain the numbers (as strings) without any quotes, commas or brackets.
Post a Comment for "Python: How To Remove [' And ']?"