簡體   English   中英

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM