有没有特定的方法可以在新行的开头输入字符?
Is there a specific way to input characters at the beginning of a new line?
目前我正在尝试实现一种在字符串中每一行的开头输入“>”的方法。
例如:
字符串:
"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([保持])
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.
使用正则表达式查找非换行符组并在之前插入一个 >
字符:
new_string = re.sub(r'[^\n]+', '>\g<0>', old_string) # be sure to import re
这应该和 print
完全一样,除了你问的:
def newprint(*args, **kwargs):
to_print = " ".join([str(a) for a in args])
print(">", "\n> ".join(to_print.splitlines()), **kwargs)
目前我正在尝试实现一种在字符串中每一行的开头输入“>”的方法。
例如:
字符串:
"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([保持])
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.
使用正则表达式查找非换行符组并在之前插入一个 >
字符:
new_string = re.sub(r'[^\n]+', '>\g<0>', old_string) # be sure to import re
这应该和 print
完全一样,除了你问的:
def newprint(*args, **kwargs):
to_print = " ".join([str(a) for a in args])
print(">", "\n> ".join(to_print.splitlines()), **kwargs)