我有一個字符串如空格分隔字符串中的每個單詞:的Python:用引號括起來
line="a sentence with a few words"
我想上述轉換的一個字符串中的每一個在雙引號的話,如:
"a" "sentence" "with" "a" "few" "words"
有什麼建議嗎?
我有一個字符串如空格分隔字符串中的每個單詞:的Python:用引號括起來
line="a sentence with a few words"
我想上述轉換的一個字符串中的每一個在雙引號的話,如:
"a" "sentence" "with" "a" "few" "words"
有什麼建議嗎?
既然你說 -
我想上述轉換的字符串與每個在雙引號
的話
您可以使用下面的正則表達式 -
>>> 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"!'
或者你可以簡單的東西(更實現,但對於初學者更容易)通過搜索每個空間引用然後切割空間之間的任何東西,添加「之前和之後,然後打印它。
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"
第一個答案錯過了原帖的一個實例。最後一個字符串/單詞「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
你們是不是要拆分字符串?試試'words = line.split()' – vaultah
@vaultah我需要帶引號的字符串形式的結果。你的建議會產生一個列表。 – Ketan