如何在Python中将文本添加到字符串行的末尾?

6

如何在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."""

我希望我表述清楚了。

2个回答

7

如果字符串比较小,我会使用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')

赞同这个想法,但是你不能像那样在字符串对象上使用append。 - wim

1
首先,字符串是不可变的,因此您必须构建一个新字符串。使用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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接