Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I remove quotes using `strip('\"')`?

I can only remove the left quotes using str.strip('\"'):

with open(filename, 'r') as fp :
    for line in fp.readlines() :
        print(line)
        line = line.strip('\"')
        print(line)

Part of results:

"Route d'Espagne"

Route d'Espagne"

Using line.replace('\"', '') gets the right result:

"Route d'Espagne"

Route d'Espagne

Can anyone explain it?

like image 964
SparkAndShine Avatar asked Dec 25 '22 17:12

SparkAndShine


1 Answers

Your lines do not end with quotes. The newline separator is part of the line to and is not removed when reading from a file, so unless you include \n in the set of characters to be stripped the " is going to stay.

When diagnosing issues with strings, produce debug output with print(repr(line)) or even print(ascii(line)), to make non-printable or non-ASCII codepoints visible:

>>> line = '"Route d\'Espagne"\n'
>>> print(line)
"Route d'Espagne"

>>> print(repr(line))
'"Route d\'Espagne"\n'

Add \n to the str.strip() argument:

line = line.strip('"\n')

Demo:

>>> line.strip('"')
'Route d\'Espagne"\n'
>>> line.strip('"\n')
"Route d'Espagne"
>>> print(line.strip('"\n'))
Route d'Espagne
like image 91
Martijn Pieters Avatar answered Jan 11 '23 15:01

Martijn Pieters