简体   繁体   中英

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. 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. You can read more about Python representation here:

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.

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.

This happens because during the interpretation of the string, the "\\" is used as an escape character telling python to look at the next character.

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.

Once you actually print(string2) python interprets the string and sees the escape characters and works as expected.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM