用Python替换一行多行字符串?

时间:2017-09-12 01:55:06

标签: python string

我在python中有一个多行字符串,我想替换它的特定行号。我有一个循环遍历每一行并将行号增加1,但当我到达需要替换的行时我该怎么办?有什么建议吗?

2 个答案:

答案 0 :(得分:3)

yourstring = yourstring.split("\n")
yourstring[lineyouwant] = edit
yourstring = "\n".join(yourstring)

lineyouwant是0索引

答案 1 :(得分:1)

试试这个:

string = """line1
line2
line3
line4
line5"""
str_list = string.split('\n')
str_list[4] = "my new line value"
string = "\n".join(str_list)
print(string)