Zy Taga
Zy Taga

Reputation: 89

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.

Upvotes: 3

Views: 216

Answers (3)

U13-Forward
U13-Forward

Reputation: 71580

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

Upvotes: 1

sophros
sophros

Reputation: 16660

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

Upvotes: 1

joshmeranda
joshmeranda

Reputation: 3251

To remove leading and trailing characters from a string you will want to use the str.strip method instead:

string = "'I'm'"

string = string.strip("'")

Upvotes: 0

Related Questions