当一个句子有引号或倒逗号时,如何生成字符串?Python

2024-06-28 16:32:02 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我有这样一个句子:

Jamie's car broke "down" in the middle of the street

如何将其转换为字符串而不手动删除引号和倒逗号,如:

'Jamies car broke down in the middle of the street' 

感谢您的帮助! 谢谢你


Tags: ofthe字符串instreetmiddle手动car
3条回答

试试这个:

oldstr = """Jamie's car broke "down" in the middle of the street""" #Your problem string
newstr = oldstr.replace('\'', '').replace('"', '')) #New string using replace()
print(newstr) #print result

这将返回:

Jamies car broke down in the middle of the street

依次使用replace()

s = """Jamie's car broke "down" in the middle of the street"""

print(s.replace('\'', '').replace('"', ''))
# Jamies car broke down in the middle of the street

您可以使用regex从字符串中删除所有特殊字符,如下所示:

>>> import re
>>> my_str = """Jamie's car broke "down" in the middle of the street"""

>>> re.sub('[^A-Za-z0-9\s]+', '', my_str)
'Jamies car broke down in the middle of the street'

相关问题 更多 >