简体   繁体   中英

python - is there a intelligent way for formatting strings with quotations?

I'm using neo4j python lib to manipulate the neo4j graph database.

I need to format the cypher query like

query = 'create (n:Person {{nickname: "{0}"}}) return n;'.format(nickname)

If the nickname contains a " itself like A"B , the generated query will be

create (n:Person {nickname: "A"B"}) return n; which will raise a syntax error in cql running.

In fact the cypher query language support '' and "" to indicate a string.

So my problem is, if there is a smart way, when the variable nickname contains ' or " , the formatted string could automatically use the right quotation marks?

You can use """Lorem ipsum""" format string which allows you to use symbols and ascii chars. ie

query = """create (n:Person {{nickname: "{0}"}}) return n;""".format(nickname)

You could also use single quotes and double qoutes in the string.

You can use the repr function to format the string with proper quotation marks:

query = 'create (n:Person {{nickname: {0}}}) return n;'.format(repr(nickname))

since its behavior is exactly what you want, enclosing a given string with double quotes when the string contains a single quote, and single quotes when the string contains a double quote:

>>> print(repr("A'B"))
"A'B"
>>> print(repr('A"B'))
'A"B'

What you need is called "quotes escaping". The most simple way to do that is:

nickname='A"B'
query = 'create (n:Person {{nickname: "{0}"}}) return n;'.format(nickname.replace('"','\\"'))
print(query)

>>> 
create (n:Person {nickname: "A\"B"}) return n;

If you would like a more "formal" way, you can do following:

import json
person = {'nickname': 'A"B'}
query = 'create (n:Person {0}) return n;'.format(json.dumps(person))
print(query)

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