我有一个字符串如空格分隔字符串中的每个单词:的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