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)

Asked By: Tiny

||

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).

Answered By: Reza Keshavarz

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

>>>
Answered By: alexis

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.

Answered By: cdlane
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.