Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract numbers from string with backslash

I need to extract the numbers from a string in the following format: ‘183\118\40’. I tried:

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

output: [‘183’, ‘8’]

st.split('\\')

output: [‘183\t8 ‘]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have confused the REPRESENTATION of your string with the CONTENT of your string. The string '183\118\40' 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'183\118\40'

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading