Python:用引号括起空格分隔字符串的每个单词

时间:2015-09-24 15:50:51

标签: python string

我有一个字符串,例如:

line="a sentence with a few words"

我想用双引号中的每个单词转换上面的字符串,例如:

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

有什么建议吗?

4 个答案:

答案 0 :(得分:7)

将该行拆分为单词,将每个单词用引号括起来,然后重新加入:

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

答案 1 :(得分:4)

因为你说 -

  

我想用双引号中的每个单词将字符串中的上述内容转换为

您可以使用以下正则表达式 -

>>> 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"!'

答案 2 :(得分: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"

答案 3 :(得分: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