2015-09-24 60 views
2

我有一個字符串如空格分隔字符串中的每個單詞:的Python:用引號括起來

line="a sentence with a few words" 

我想上述轉換的一個字符串中的每一個在雙引號的話,如:

"a" "sentence" "with" "a" "few" "words" 

有什麼建議嗎?

+0

你們是不是要拆分字符串?試試'words = line.split()' – vaultah

+0

@vaultah我需要帶引號的字符串形式的結果。你的建議會產生一個列表。 – Ketan

回答

6

拆分行成的話,用引號括每個字,然後重新加入:

' '.join('"{}"'.format(word) for word in line.split(' ')) 
+0

這很快!謝謝。 – Ketan

3

既然你說 -

我想上述轉換的字符串與每個在雙引號

的話

您可以使用下面的正則表達式 -

>>> line="a sentence with a few words" 
>>> import re 
>>> re.sub(r'(\w+)',r'"\1"',line) 
'"a" "sentence" "with" "a" "few" "words"' 

這將考慮到標點​​符號等,以及(如果這真的是你想要的東西) -

>>> line="a sentence with a few words. And, lots of punctuations!" 
>>> re.sub(r'(\w+)',r'"\1"',line) 
'"a" "sentence" "with" "a" "few" "words". "And", "lots" "of" "punctuations"!' 
0

或者你可以簡單的東西(更實現,但對於初學者更容易)通過搜索每個空間引用然後切割空間之間的任何東西,添加「之前和之後,然後打印它。

quote = "they stumble who run fast" 
first_space = 0 
last_space = quote.find(" ") 
while last_space != -1: 
    print("\"" + quote[first_space:last_space] + "\"") 
    first_space = last_space + 1 
    last_space = quote.find(" ",last_space + 1) 

上面的代碼會爲你輸出如下:

"they" 
"stumble" 
"who" 
"run" 
0

第一個答案錯過了原帖的一個實例。最後一個字符串/單詞「fast」未打印。 該解決方案將打印最後一個字符串:

quote = "they stumble who run fast" 

start = 0 
location = quote.find(" ") 

while location >=0: 
    index_word = quote[start:location] 
    print(index_word) 

    start = location + 1 
    location = quote.find(" ", location + 1) 

#this runs outside the While Loop, will print the final word 
index_word = quote[start:] 
print(index_word) 

這是結果:

they 
stumble 
who 
run 
fast 
+0

此代碼有縮進問題。 –

+0

謝謝@StephenRauch,我刪除了多餘的if語句 – Conor

+0

你現在有一個'::' –

相關問題