简体   繁体   中英

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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM