[英]Search for key word and convert the output into new line after it matches in python
[英]python replace a word with empty line or append a new line after the word
如何在单词后添加空行,或者如何在特定单词处将短语拆分为段落格式并将其值分配给另一个字符串
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存储字符串的方式,您真的不能不打印它而这样做。
为什么:
当您在字符串中放置换行符"\\n"
,直到真正要解释字符串时,python才会考虑到这一点。
发生这种情况是因为在字符串解释期间, "\\"
用作转义字符,告诉python查看下一个字符。
在您真正进行解释之前,python只是将字符串的值保存在变量中,在这种情况下, string2 = "hello \\n\\t this is test"
,并且它没有解释它,因此未查找转义字符在,因此python不会显示您期望的格式。
一旦您实际print(string2)
python就会解释该字符串并查看转义字符并按预期工作。
结论:
您的代码没有错误,您应该能够使用与现在完全相同的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.