2015-09-24 62 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

你现在有一个'::' –

相关问题