How to format python string with both double and single quotes
Question:
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)
Answers:
I think 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, worldn"
>>> my_string
'Hello, worldn'
>>> 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.
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 think 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, worldn"
>>> my_string
'Hello, worldn'
>>> 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.