当前我正在尝试实现一种在字符串中每个单独行的开头输入“">”的方法。
一个例子是:
字符串:
"Hello how are you!
Python is cool!"
现在这就是一个大字符串,有一个换行符。但是有没有一个函数可以确定换行的时间和位置呢?正如我上面所说,我想在每个新行的开头添加一个“>”。就像这样:
字符串:
">Hello how are you!
>Python is cool!"
注意:该字符串不是永久设置的,因此我必须解决此问题。
希望这是有道理的,感谢您的帮助!
最佳答案
只需拆分行并连接即可:
lines = """Hello how are you!
Python is cool!"""
for line in lines.splitlines():
if line:
print(">" + line)
else:
print(line)
>Hello how are you!
> Python is cool!
要获取新字符串并保留换行符,请设置 keepends=True:
new_s = "".join([">{}".format(line) if line.strip() else line
for line in lines.splitlines(True)])
print(new_s)
>Hello how are you!
> Python is cool!
str.splitlines([keepends])
Return a list of the lines in the string, breaking at line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true.
关于python - 有没有特定的方法可以在新行的开头输入字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30140778/