简体   繁体   English

如何从字符串中删除特定字符

[英]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:您的代码有一些缺陷:

  1. Why are you iterating over the string if the only thing you need to check is the first and the last character?如果您唯一需要检查的是第一个和最后一个字符,为什么还要遍历字符串?
  2. While iterating a string you should not change it.在迭代一个字符串时,你不应该改变它。 It leads to unexpected and undesired consequences.它会导致意想不到的和不希望的后果。
  3. Your Boolean logic seems odd.您的 Boolean 逻辑似乎很奇怪。
  4. You are replacing all of the quotes in the first loop.您正在替换第一个循环中的所有引号。

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

To remove leading and trailing characters from a string you will want to use thestr.strip method instead:要从字符串中删除前导和尾随字符,您需要使用str.strip方法:

string = "'I'm'"

string = string.strip("'")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM