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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With