[英]python replace a word with empty line or append a new line after the word
How do I append an empty line after a word or how can I split a phrase into a paragraph format at a particular word and assign its value to another string 如何在单词后添加空行,或者如何在特定单词处将短语拆分为段落格式并将其值分配给另一个字符串
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
My code: 我的代码:
string = "hello this is test"
string2 = string.replace("hello","hello \n\t")
But my output is 但是我的输出是
"'hello \n\t this is test'"
But when i do: 但是当我这样做时:
print(string2)
my result is in the format of what i need 我的结果是我需要的格式
"hello
this is a test"
Question: 题:
How can i do this without printing the string? 不打印字符串怎么办?
Your code is fine. 您的代码很好。 If you use it as a variable or store it in a text file, you will get the expected output.
如果将其用作变量或将其存储在文本文件中,则将获得预期的输出。 However, when you do the command
string2 = string.replace("hello","hello \\n\\t")
Python prints out the way it sees the string, before it is fully interpreted. 但是,当执行命令
string2 = string.replace("hello","hello \\n\\t")
Python会在完全解释字符串之前打印出它看到字符串的方式。 In other words, it prints the character representation of the value. 换句话说,它打印值的字符表示。 Keep on working with the variable--it will present the result you need, just ignore the unwanted output of the
string2 =
command. 继续使用该变量-它会显示您需要的结果,只是忽略
string2 =
命令的不需要的输出。 You can read more about Python representation here: 您可以在此处阅读有关Python表示的更多信息:
http://satran.in/2012/03/14/python-repr-str.html http://satran.in/2012/03/14/python-repr-str.html
Happy coding and best of luck! 祝您编程愉快,万事如意!
Answer: 回答:
You really can't do this without printing this because of the way python stores a string. 由于python存储字符串的方式,您真的不能不打印它而这样做。
Why: 为什么:
When you place a newline "\\n"
in your string python doesn't take this into account until you want to actually interpret the string. 当您在字符串中放置换行符
"\\n"
,直到真正要解释字符串时,python才会考虑到这一点。
This happens because during the interpretation of the string, the "\\"
is used as an escape character telling python to look at the next character. 发生这种情况是因为在字符串解释期间,
"\\"
用作转义字符,告诉python查看下一个字符。
Until you actually do this interpretation, python just holds the value of the string in the variable, in this case string2 = "hello \\n\\t this is test"
, and it is not interpreting it, so the escape character isn't looked at, and therefor python doesn't display the formatting you may expect. 在您真正进行解释之前,python只是将字符串的值保存在变量中,在这种情况下,
string2 = "hello \\n\\t this is test"
,并且它没有解释它,因此未查找转义字符在,因此python不会显示您期望的格式。
Once you actually print(string2)
python interprets the string and sees the escape characters and works as expected. 一旦您实际
print(string2)
python就会解释该字符串并查看转义字符并按预期工作。
Conclusion: 结论:
You have no error in your code and you should be able to work on with the string being exactly as it is now. 您的代码没有错误,您应该能够使用与现在完全相同的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.