我有一个字符串,例如:
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)
有什么建议?
将该行拆分为单词,将每个单词用引号括起来,然后重新加入:
' '.join('"{}"'.format(word) for word in line.split(' '))
Run Code Online (Sandbox Code Playgroud)
既然你说——
我想用双引号将上面的每个单词转换成一个字符串
您可以使用以下正则表达式 -
>>> 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)
| 归档时间: |
|
| 查看次数: |
3490 次 |
| 最近记录: |