[英]Add text to end of all lines in string
Say I have this string: 说我有这个字符串:
"""
iris
jonah
car
donut
"""
How do I add something at the end of all the lines? 如何在所有行的末尾添加内容? The amount of lines in the string may vary from time to time. 字符串中的行数可能会不时变化。
Something like: 就像是:
l = duplicate.split('\n')
l[1]+= 'X'
l = '\n'.join(l)
print(l)
Duplicate being the string's name. 重复的是字符串的名称。
This code only adds 'X' to the end of line 1. 此代码仅在第1行的末尾添加“ X”。
How can I do this for every line? 如何为每一行做到这一点?
Desired output: 所需的输出:
"""
irisX
jonahX
carX
donutX
"""
Thanks! 谢谢!
Just use str.replace()
: 只需使用str.replace()
:
addition = 'X'
new_string = duplicate.replace('\n', addition + '\n')
删除l[1]+= 'X'
行,并将l = '\\n'.join(l)
更改为l = 'X\\n'.join(l)
。
First, split as you did duplicate
on '\\n'
: 首先,像在'\\n'
上duplicate
进行拆分:
splitted = duplicate.split('\n')
Then append 'x'
at the end of each line with a for
, and join these line on '\\n'
. 然后在每行的末尾附加一个for
'x'
,并在'\\n'
上加入这些行。 I do both operations in a signle line: 我在标志行中同时执行这两项操作:
"\n".join(line + "x" for line in splitted)
If you're not familiar with generator expressions, this is somewhat similar to: 如果您不熟悉生成器表达式,则此方法类似于:
withSuffixes = []
for line in l:
withSuffixes.append(splitted + "x")
"\n".join(withSuffixes)
您可以使用map将功能应用于通过split
获得的列表的所有元素,然后join
这些元素join
到单个字符串中:
"\n".join(map(lambda word: word+"x", s.split("\n")))
Try this, uses list comprehension to add 'X' to each line and then joins it by a newline character. 尝试此操作,使用列表推导将'X'添加到每行,然后通过换行符将其连接。
duplicate = """
iris
jonah
car
donut
"""
l = duplicate.split('\n')
l = [line + 'X' for line in l]
final = '\n'.join(l)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.