删除字符串引用而不切片?

2024-04-23 07:33:21 发布

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

我想分析输入的字符串,但引号干扰了我的分析。如何在不使用切片/索引的情况下删除引号?有什么类似的吗字符串.strip()表示引用或简单的等价表达式?谢谢,伙计们!你知道吗


Tags: 字符串表达式情况切片引号strip等价伙计
3条回答

使用replace

string = "'hello'"

print(string.replace("'",""))
# hello

strip完全符合您的目的。只需要求它删除引用:

>>> string = "'hello'"
>>> print(string.strip("'"))
hello

您可以执行以下操作之一:

string.strip("'") # strips single quotes away
string.strip('"') # strips double quotes
string.strip("'\"") # both single and double quotes. The double quote in the middle is 'escaped' by the backslash character

或者

string = string.replace("'", "") # replaces single quotes in the string with nothing
string = string.replace('"', '') # for double quotes

相关问题 更多 >