在不知道切片编号的情况下,如何在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."""我希望我说清楚了。
发布于 2012-01-12 12:17:16
如果字符串相对较小,我会使用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')发布于 2012-01-12 12:47:18
首先,字符串是不可变的,因此您必须构建一个新的字符串。在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
chttps://stackoverflow.com/questions/8830029
复制相似问题