I am trying to split a string of numbers separated by commas into a list but it it giving me this error:
TypeError: 'str' object cannot be interpreted as an integer
This is what I've tried:
numbers = "1, 2, 3, 4, 5, 500, 600, 800"
numbers_list = numbers.split(",", " ")
print(numbers_list)
CodePudding user response:
The .split
method only takes one string argument, the second argument is an integer and specifies the maximum number of splits. So, if the second argument was 2, it would only split the string up to 2 times, which would get you a list with a length of 3. But since you don't care about exactly how many times the string gets split, you can ignore the second argument. You would probably also want to get rid of the space in between the numbers, so you would also include that along with the comma. With all this taken into account, you final code would look like this:
numbers_list = numbers.split(", ")
CodePudding user response:
import re
numbers = "1, 2, 3, 4, 5, 500, 600, 800"
val = re.sub(r'[^\w]', ' ', numbers)
li = val.split(" ")
li2 = []
for i in li:
if i == "":
pass
else:
li2.append(i)
print(li2)
import regex, And try this code