Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 tried the replace() and translate() buils-in methods but neither of them does what I want. 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.

like image 408
Zy Taga Avatar asked Sep 17 '26 07:09

Zy Taga


2 Answers

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.
  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, e.g.

"'''three-one quotes'".strip("'")
> three-one quotes
like image 180
sophros Avatar answered Sep 18 '26 20:09

sophros


Just use strip:

print(string.strip("'"))

Otherwise try this:

if (string[0] == "'") or (string[-1] == "'"):
    string = string[1:-1]
print(string)

Both codes output:

I'm
like image 42
U12-Forward Avatar answered Sep 18 '26 21:09

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!