random string
this is 34 the string 3 that, i need 234
random string
random string
random string
random string
random string
this is 1 the string 34 that, i need 22
random string
random string
random string
random string
random string
this is 35 the string 55 that, i need 12
random string
random string
random string
random string
Within one string there are multiple lines. One of the lines is repeated but with different numbers each time. I was wondering how can I store the numbers in those lines. The numbers will always be in the same position in the line, but can be any number of digits.
Edit: The random strings could have numbers in them as well.
This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.
You can extract a substring in the range start <= x < stop with [start:step] . If start is omitted, the range is from the beginning, and if end is omitted, the range is to the end. You can also use negative values. If start > end , no error is raised and an empty character '' is extracted.
Method #2: Using %d operator This operator can be used to format the string to add the integer. The “d” represents that the datatype to be inserted to string is an integer.
Use regular expressions:
>>> import re
>>> comp_re = re.compile('this is (\d+) the string (\d+) that, i need (\d+)')
>>> s = """random string
this is 34 the string 3 that, i need 234
random string
random string
random string
random string
random string
this is 1 the string 34 that, i need 22
random string
random string
random string
random string
random string
this is 35 the string 55 that, i need 12
random string
random string
random string
random string
"""
>>> comp_re.findall(s)
[('34', '3', '234'), ('1', '34', '22'), ('35', '55', '12')]
By using regular expressions
import re
s = """random string
this is 34 the string 3 that, i need 234
random string
random string
random string
"""
re.findall('this is (\d+) the string (\d+) that, i need (\d+)', s)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With