如何在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."""
我希望我表述清楚了。
如何在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."""
我希望我表述清楚了。
如果字符串比较小,我会使用str.split('\n')
将其分割成一个字符串列表。然后更改您想要的字符串,再将列表连接起来:
l = mystr.split('\n')
l[2] += ' extra text'
mystr = '\n'.join(l)
replace
。例如,如果该行以x
结尾,则可以执行。mystr.replace('x\n', 'x extra extra stuff\n')
mystring
对象上的方法splitlines
(这样您就不必显式指定行尾字符),然后按照您想要的方式将它们连接到一个新字符串中。>>> mystring = """
... a
... b
... c"""
>>> print mystring
a
b
c
>>> mystring_lines = mystring.splitlines()
>>> mystring_lines[2] += ' SPAM'
>>> print '\n'.join(mystring_lines)
a
b SPAM
c