[英]How to remove a specific character from a string
I'm trying to remove the single quotation marks from "'I'm'" to have "I'm" in the end.我试图从 "'I'm'" 中删除单引号以在最后有 "I'm"。 I tried the replace() and translate() buils-in methods but neither of them does what I want.
我尝试了 replace() 和 translate() 内置方法,但它们都不符合我的要求。 This is what I tried
这是我试过的
string = "'I'm'"
for ch in string:
if ch == "'" and (string[0] == ch or string[-1] == ch):
string = string.replace(ch, "")
I tried other ways but keeps on returning "Im" as output.我尝试了其他方法,但一直以 output 的形式返回“Im”。
Your code has a few flaws:您的代码有一些缺陷:
What would work is this:什么会起作用是这样的:
if string[0] == "'" and string[-1] == "'" and len(string) > 1:
string = string[1:-1]
Where you do pretty much the same checks you want but you just remove the quotations instead of alternating the inner part of the string.您可以在其中执行与您想要的几乎相同的检查,但您只需删除引号而不是交替字符串的内部部分。
You could also use string.strip("'")
but it is potentially going to do more than you wish removing any number of quotes and not checking if they are paired, eg您也可以使用
string.strip("'")
但它可能会比您希望删除任意数量的引号而不检查它们是否配对做的更多,例如
"'''three-one quotes'".strip("'")
> three-one quotes
Just use strip
:只需使用
strip
:
print(string.strip("'"))
Otherwise try this:否则试试这个:
if (string[0] == "'") or (string[-1] == "'"):
string = string[1:-1]
print(string)
Both codes output:两个代码 output:
I'm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.