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