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

mkc*_*mkc 2 python string

我有一个字符串,例如:

line="a sentence with a few words"
Run Code Online (Sandbox Code Playgroud)

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

 "a" "sentence" "with" "a" "few" "words"
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Dan*_*man 7

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

' '.join('"{}"'.format(word) for word in line.split(' '))
Run Code Online (Sandbox Code Playgroud)


Ana*_*mar 5

既然你说——

我想用双引号将上面的每个单词转换成一个字符串

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

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

这也会考虑标点符号等(如果这确实是您想要的)-

>>> 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"!'
Run Code Online (Sandbox Code Playgroud)