简体   繁体   中英

How to format python string with both double and single quotes

I need to create a python string like:

'A' "B"

Which I think should be reliably produced using:

my_string = "'A' \"B\""

What I get here is:

'\'A\' "B"'

Which inst what we want. Help!

(Why... InfluxDB uses both single and double quotes in queries)

I thing you get that output in python shell, while entering only the name of the string. You'll get the output you want if you use print(string_name).

Your string is correct the way you wrote it. The output you see is confusing you because you are seeing the " repr " (unambiguous) form of the string, presumably because you just typed the variable name at the prompt. Note that this form also adds a pair of (single) quotes around the string, no matter what you put in your variable.

Display the string with print(my_string) to see what it really contains.

>>> my_string = "Hello, world\n"
>>> my_string
'Hello, world\n'
>>> print(my_string)
Hello, world

>>>

You can take advantage of Python having three types of quotes to eliminate backslashes on entry:

>>> my_string = ''''A' "B"'''
>>> my_string
'\'A\' "B"'
>>> print(my_string)
'A' "B"
>>> 

As you can see, Python is adding backslashes to properly display the string in its interpreter, it's not misunderstanding your input. Upon print() everything comes out as desired.

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