pythonstringnumbersbackslash

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 ']


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.