Home > other >  How to convert list string to integer using python
How to convert list string to integer using python

Time:01-20

I have the following string:

s = "[(12, 45), (13,67), (14, 88)]"

I would like to extract only the numbers and print it.

What I tried so far?

s.partition(',')[0]

or 

[int(word) for word in s.split() if word.isdigit()]

Since it is a string it prints along with [(. How do I print only the numbers?

Desired output: 12 45 13 67 14 88

CodePudding user response:

Using re.findall should work here:

s = "[(12, 45), (13,67), (14, 88)]"
nums = [int(x) for x in re.findall(r'\d ', s)]
print(nums)  # [12, 45, 13, 67, 14, 88]

To get your exact printed output, use:

s = "[(12, 45), (13,67), (14, 88)]"
output = '\n'.join([x for x in re.findall(r'\d ', s)])
print(output)

#12
#45
#13
#67
#14
#88

CodePudding user response:

s = "[(12, 45), (13,67), (14, 88)]"
list_of_tuples = eval(s)
print(list_of_tuples)

for (num1,num2) in list_of_tuples:
    print(num1,num2,end=" ")

CodePudding user response:

A simple list comprehension could also work here where we repeatedly strip brackets:

out = [int(sub.strip(' ()')) for sub in s.strip('[()]').split(',')]

Output:

[12, 45, 13, 67, 14, 88]

CodePudding user response:

this will work great:

[int(s) for s in txt.split() if s.isdigit()]

you can also use re:

import re
re.findall(r'\d ', string)

CodePudding user response:

you can use the replace method

s.replace("[(","").replace(")]","").replace("(","").replace("),","").replace(","," ")
  •  Tags:  
  • Related