BananaMaster
BananaMaster

Reputation: 577

Replace first and last character in string if the character is X

I want to replace the double quotes only if the string starts and ends with double quotes. Below are some examples:

str = '"hello"'

would become

str = 'hello'

but

str = 'hello"'

would stay as is because it only ends with double quotes. What I do now is

if str.startswith('"') and str.endswith('"'):
    str = str[1:-1]

but I'm pretty sure there's a better way of doing this that I can't figure out.

Upvotes: 0

Views: 2406

Answers (1)

Daniel
Daniel

Reputation: 42778

A simple other way would be:

if str and str[0] == str[-1] == '"':
    str = str[1:-1]

Upvotes: 1

Related Questions