如何在python中的多行字符串中的某行的末尾写入一些文本,而无需知道切片编号?这里有一个例子:如何将文本添加到字符串中一行的末尾? - 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中的多行字符串中的某行的末尾写入一些文本,而无需知道切片编号?这里有一个例子:如何将文本添加到字符串中一行的末尾? - 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')
首先,字符串是不可变的,所以你必须建立一个新的字符串。使用方法splitlines
上的mystring
对象(以便您不必显式指定行结束字符),然后将它们连接到一个新字符串,但是您希望。
>>> 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
+1对于一般的想法,但不能像这样使用附加在字符串对象上。 – wim 2012-01-12 04:48:13
感谢您的发现。修复了代码。 – thesamet 2012-01-12 05:07:22
哈哈,哇,这比我想象的要容易得多。谢谢。 – uncleshelby 2012-01-13 00:29:56