3

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.

3 Answers 3

1

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 
Sign up to request clarification or add additional context in comments.

Comments

1

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 

Comments

0

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("'") 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.