Reputation: 89
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
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
Reputation: 16660
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, e.g.
"'''three-one quotes'".strip("'")
> three-one quotes
Upvotes: 1
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