python 用空行替换单词或在单词后添加新行

标签 python replace newline

如何在单词后附加空行,或者如何在特定单词处将短语拆分为段落格式并将其值分配给另一个字符串

input: "hello"

output: "hello"
        #empty line


input : "hello this is test"   #after hello i want to split the data into new line

output : "hello   
    this is test" #New line and tab

我的代码:

string = "hello this is test"  
string2 = string.replace("hello","hello \n\t")

但是我的输出是

"'hello \n\t this is test'"

但是当我这样做时:

print(string2) 

我的结果是我需要的格式

"hello   
   this is a test"

问题:
如何在不打印字符串的情况下执行此操作?

最佳答案

你的代码没问题。如果将其用作变量或将其存储在文本文件中,您将获得预期的输出。 但是,当您执行命令 string2 = string.replace("hello","hello\n\t") 时,Python 会打印出它之前看到字符串的方式它得到了充分的解释。换句话说,它打印值的字符表示形式。继续使用该变量 - 它将显示您需要的结果,只需忽略 string2 = 命令的不需要的输出。 您可以在此处阅读有关 Python 表示的更多信息:

http://satran.in/2012/03/14/python-repr-str.html

编码愉快,祝你好运!

关于python 用空行替换单词或在单词后添加新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32188056/

相关文章:

c++ - 阻止 getline 丢弃换行符

python - 使用 Windows 解析 Pandas 中的单个小数小时

python - "with"语句内的交互模式

xml - 通过 Powershell 替换 xml 文件中的文本

php - 在搜索结果中突出显示关键字

python - 错误文本替换代码 :

Java 打印 : Windows vs Linux

python - 如何在 ldap3 中读取给定 DN 的属性(如果没有过滤器,如何使用 ldap3 进行搜索)

python - 检查 tmpl_context 中是否存在变量(Python、Pylons、Genshi)?

string - 如何向 Ansible 变量添加新行 "\n"字符