如何在字符串的行尾添加文本? - 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."""
我希望我说得够清楚。
2 个回答
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
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')