Daniel Cook
Daniel Cook

Reputation: 1896

Parsing strings with single quotation marks in Python

If I have a string like: 'I can't parse this' with a single quotation mark in between, how can I remove that without getting a syntax error, and return ICANTPARSETHIS? I know that it would work if it was "I can't parse this" instead, but I am looking at a problem where the potential input might not have double quotation marks surrounding it.

Upvotes: 0

Views: 4826

Answers (3)

actionseth
actionseth

Reputation: 27

So my understanding is that you want to remove the apostrophe on the "can't"?

'I can't parse this'.replace("'", "")
>>> 'I cant parse this'

or if you have it in a variable:

s = 'I can\'t parse this'
s.replace("'", "")
>>> 'I cant parse this'

Edit: As pointed out the second example was a syntax error without the escape character on the apostrophe.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121884

You've misunderstood something here. There is no problem here at all.

Syntax errors only apply to source code. String values are not source code.

If your source code uses string literals, Python parses those and produces a string value. The string literal can have a syntax error in it, but if without errors, it will produce a string value that is just that, a value.

In the Python interpreter such string values are represented using the same format as a string literal, for ease of debugging and copying back into the interpreter. Rest assured that the Python interpreter knows how to escape quotes in such values correctly:

>>> """Text with a single quote: '"""
"Text with a single quote: '"""
>>> """We can use a double quote too: ". See?"""
'We can use a double quote too: ". See?'
>>> """Even mixing " and ' is not a problem."""
'Even mixing " and \' is not a problem.'

I used triple-quoted literal syntax there, but Python echos alternatives that use the minimum quoting style required, and escapes quote symbols as needed.

Upvotes: 4

Joran Beasley
Joran Beasley

Reputation: 113978

print "Parse 'this string' to something".split()
print re.findall(some_pattern,"this is a string with `internal quotation` marks")
print 'quotes' == "quotes" == """quotes""" == '''quotes''' == u'quotes' == u"quotes"

Im not sure what your question is ... but these two examples demonstrate that you can parse strings with internal quote marks

also demonstrates that quotes are all the same basically

Upvotes: 2

Related Questions