简体   繁体   English

将文本添加到字符串中所有行的末尾

[英]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.

相关问题 如何在文件中所有行的末尾添加字符串 - How to add strings in the file at the end of all lines 如何在某些特定行的末尾添加文本 - How to add text at end of some specific lines 在文本文件的特定范围内的多行末尾添加/追加文本 - Add/Append text to the end of multiple lines in a specific range in a text file 搜索开始字符串和搜索结束字符串,然后在python中打印开始到结束行之间的所有行 - search begin string and search end string then print all lines between begin to end lines in python 将行号和字数添加到文本文件的行尾 - Add row number and word count to end of lines in text file 如何在字符串中的行尾添加文本? - Python - How to add text to the end of a line in a string? - Python 如何在python中几个文件的某些行的末尾添加一个字符串 - how to add a string at the end of some lines of several files in python 将特定字符串添加到文件中特定行的末尾 - Add specific string to the end of specific lines from files 替换目录中所有文本文件的所有行中的字符串值 - Replace a string value from all the lines of all the text files in a directory 高效获取大型文本文件中以给定字符串开头的所有行 - Efficiently get all lines starting with given string for a large text file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM