如何在python中的多行字符串中的一行末尾写一些文本而不知道切片编号?这是一个例子:
mystring="""
This is a string.
This is the second Line. #How to append to the end of this line, without slicing?
This is the third line."""
Run Code Online (Sandbox Code Playgroud)
我希望我很清楚.
如果字符串相对较小,我会用str.split('\n')它将其分解为字符串列表.然后更改所需的字符串,并加入列表:
l = mystr.split('\n')
l[2] += ' extra text'
mystr = '\n'.join(l)
Run Code Online (Sandbox Code Playgroud)
此外,如果您可以唯一地标识要附加到的行的结尾,则可以使用replace.例如,如果该行结束x,那么您可以这样做
mystr.replace('x\n', 'x extra extra stuff\n')
Run Code Online (Sandbox Code Playgroud)