python - 有没有特定的方法可以在新行的开头输入字符?

标签 python string formatting

当前我正在尝试实现一种在字符串中每个单独行的开头输入“">”的方法。

一个例子是:

字符串:

"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/

相关文章:

java - String.valueOf(int i) 和只打印 i 的区别

Excel 整数到 bool 条件

java - PeriodFormatter - 如果小时或分钟恰好是一位数字,如何在前面加上 0?

user-interface - 绘制图形的工具,返回 graph6 代码或邻接矩阵

python - Django 表单 - 如何不验证?

python - 如何在 Selenium 中选择表格单元格中的所有文本

python - 如何在pycharm终端自动打开url(不是点击打开)http ://127. 0.0.1 :8000 python manage. py runserver

android - 如何从原始文件中读取并在 String.format 中使用

c - 如何在c中解析小时格式?

python - 在 Python 中将数字字符串的键拆分为单个数字键