Extract numbers from string with backslash

Question:

I need to extract the numbers from a string in the following format: ‘18311840’. I tried:

st = '18311840'
re.findall(r"[-+]?(?:d*.d+|d+)", st)

output: [‘183’, ‘8’]

st.split('\')

output: [‘183t8 ‘]

Asked By: Naomi Fridman

||

Answers:

You have confused the REPRESENTATION of your string with the CONTENT of your string. The string '18311840' contains 6 characters, NONE of which are backslashes. The "11" is an octal character constant. Octal 11 is decimal 9, which is the tab character. The "40" is also an octal character constant. Octal 40 is decimal 32, which is space.

If you really want that literal string, you need one of:

st = '183\118\40'
st = r'18311840'

Note that this only happens because you have typed it as a Python string constant. If you read that line in from file, it will work just fine.

Answered By: Tim Roberts

It is recommended to use ‘/xx’, str = ‘xx’ default will be transferred by default.

Answered By: user19743767
st = '18311840'
print(st)

If you try printing this, you will see that this is the output

'183t8 '

This is not in your required format because of the backslash or escape character() used. To solve this issue, use raw strings. To convert your string into a raw string, do this

st = r'18311840'

If you do not want to use raw strings, save it as

st = '183\118\40'

If you try printing this, you will see that this is the output

'183\118\40'

As you can see, the escape character has been itself escaped by using another escape character after it.

Now, to get the required number values from this, use string manipulation method split() with the delimiter arguement. Like so,

st.split("\")

Note that here we again escape the escape character with another backslash to set the delimiter as the literal / character.

Now,

print(st)

will give you your required output, that is,

['183', '118', '40']

Now you are ready to further process this list of strings.

If you want a list of integers instead, try

int_list = [int(x) for x in st.split('\')]

Now visualise the output,

>>>print(int_list)
[183, 118, 40]
Answered By: Akshay Dongare
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.