简体   繁体   English

更换新的换行

[英]Replacing new line feed

I'm attempting to write extra text to the first line of this multi-line string using replace , and it doesn't work: 我正在尝试使用replace将多余的文本写入此多行字符串的第一行,但不起作用:

somestr = """For example
("""

print somestr.replace('\\n(', ' you can find')

I'm expecting the following result: 我期待以下结果:

For example you can find
(

Edit 编辑

This string comes from a row object: 此字符串来自行对象:

cursor.execute("SELECT col1 FROM tbl")
row = cursor.fetchone()
somestr = str(row.col1)

The output of pprint.pprint(locals()) gives: pprint.pprint(locals())的输出给出:

{'somestr': '\n\nFor example\n(\n'}

Don't escape the newline character and it'll work just fine; 不要逃脱换行符 ,它会很好地工作; do include the original text if you want to insert rather than replace: 如果要插入而不是替换,请包含原始文本:

somestr.replace('\n(', ' you can find\n(')

The original string does not contain the character sequence \\ , n , ( , but your code is trying to replace just that. Instead, there is a newline character followed by ( in that string, and to create the newline character you need to use \\n , not \\\\n . 原来的字符串包含字符序列\\n(但你的代码试图只是替换,取而代之的是一个换行符之后(在该字符串,并创建你需要使用换行符\\n而不是\\\\n

Demo: 演示:

>>> somestr = """For example
... ("""
>>> print somestr.replace('\n(', ' you can find\n(')
For example you can find
(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM