[Python-de] Textwrap mit Backslash
Stefan Schwarzer
sschwarzer at sschwarzer.net
Mo Nov 11 12:36:44 CET 2013
Hi Ole,
On 2013-11-11 12:05, Olе Streicher wrote:
> Das Problem sind hier die fehlenden Backslashes am Ende der
> fortgesetzten Zeilen. Wie bekomme ich die dahin?
ich weiß nicht, ob ich es nicht noch einfacher geht, aber
spontan fällt mir `re.sub` mit `MULTILINE`-Flag ein:
In [1]: import re
In [2]: text = """Dies ist ein
...: mehrzeiliger
...: Text."""
In [7]: print re.sub("$", " \\\\", text, flags=re.MULTILINE)
Dies ist ein \
mehrzeiliger \
Text. \
Den Backslash am Ende kannst du folgendermaßen loswerden:
In [9]: text2 = re.sub("$", " \\\\", text, flags=re.MULTILINE)
In [10]: print text2
Dies ist ein \
mehrzeiliger \
Text. \
In [11]: print re.sub(r"[\s\\]+$", "", text2)
Dies ist ein \
mehrzeiliger \
Text.
(hier _ohne_ `MULTILINE`-Flag).
Was _mich_ jetzt nur noch interessiert, ist, warum ich
für den Ersetzungs-String _vier_ Backslashes schreiben
muss. Ich hatte es mit zwei Backslashes versucht, aber bakam
dann:
In [6]: print re.sub("$", " \\", text, flags=re.MULTILINE)
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-6-25bd5b1b5476> in <module>()
----> 1 print re.sub(r"$", " \\", text, flags=re.MULTILINE)
/usr/lib64/python2.7/re.pyc in sub(pattern, repl, string, count, flags)
149 a callable, it's passed the match object and must return
150 a replacement string to be used."""
--> 151 return _compile(pattern, flags).sub(repl, string, count)
152
153 def subn(pattern, repl, string, count=0, flags=0):
/usr/lib64/python2.7/re.pyc in _subx(pattern, template)
268 def _subx(pattern, template):
269 # internal: pattern.sub/subn implementation helper
--> 270 template = _compile_repl(template, pattern)
271 if not template[0] and len(template[1]) == 1:
272 # literal replacement
/usr/lib64/python2.7/re.pyc in _compile_repl(*key)
255 p = sre_parse.parse_template(repl, pattern)
256 except error, v:
--> 257 raise error, v # invalid expression
258 if len(_cache_repl) >= _MAXCACHE:
259 _cache_repl.clear()
error: bogus escape (end of line)
Ich habe auch festgestellt, dass ich statt
re.sub("$", " \\\\", text, flags=re.MULTILINE)
auch
re.sub("$", r" \\", text, flags=re.MULTILINE)
schreiben kann. Aber das ist nicht weniger "mysteriös".
Viele Grüße
Stefan
Mehr Informationen über die Mailingliste python-de