Delete wrapped lines

I want to remove the returned lines of text wrapped in a specific width. eg.

import re
x = 'the meaning\nof life'
re.sub("([,\w])\n(\w)", "\1 \2", x)
'the meanin\x01 \x02f life'

I want to return the meaning of life. What am I doing wrong?

+4
source share
2 answers

You need to run away \like this:

>>> import re
>>> x = 'the meaning\nof life'

>>> re.sub("([,\w])\n(\w)", "\1 \2", x)
'the meanin\x01 \x02f life'

>>> re.sub("([,\w])\n(\w)", "\\1 \\2", x)
'the meaning of life'

>>> re.sub("([,\w])\n(\w)", r"\1 \2", x)
'the meaning of life'
>>>

If you do not avoid this, the output will be \1, therefore:

>>> '\1'
'\x01'
>>> 

To do this, we need to use '\\\\'or r'\\'to display the signal \in Python RegEx.

However, about this, from this answer :

, ( , "" , ).

:

, ('\'), . Python .

, RE, \section, LaTeX. , , , . , , \\section. , re.compile(), \\section. , Python, .


, brittenb, RegEx :

>>> x = 'the meaning\nof life'
>>> x.replace("\n", " ")
'the meaning of life'
>>> 
+3

; Python, regex ; \1 python escape-, :

re.sub(r"([,\w])\n(\w)", r"\1 \2", x)

, .

. HOWTO Python.

:

>>> import re
>>> x = 'the meaning\nof life'
>>> re.sub(r"([,\w])\n(\w)", r"\1 \2", x)
'the meaning of life'

; str.splitlines(), , str.join():

' '.join(ex.splitlines())

, , .

+2

Source: https://habr.com/ru/post/1620877/


All Articles