简体   繁体   中英

Python string literals - including single quote as well as double quotes in string

I want to join this series of strings:

my_str='"hello!"' + " it's" + ' there'

Want the result to be:

my_str
Out[65]: '"hello!" it's there'

But I get:

my_str
Out[65]: '"hello!" it\'s there'

I have tried a few iterations but none seem to work.

The result is correct. Single quotes have to be escaped in single quoted strings. The same for double quotes.

If you try print the result, you'll see that it's as you expected.

>>> print(my_str)
"hello!" it's there

if you use print command you will see as you want...

>>> my_str='"hello!"' + " it's" + ' there'
>>> my_str
'"hello!" it\'s there' #Count printed characters. You will count 22
>>> print my_str
"hello!" it's there
#Now count characters. 19
>>> len(my_str)
19
#see count of characters.

Using only "my_str" without any command/function shows only memory. but if you want process with string u will get "'" without "\\"...

print my_str will print your string as

'"hello!" it's there'

You can also do that stuff in another way using my_str.decode('ascii')

new_str = my_str.decode('ascii')
print new_str

It will print the string as:

"hello!" it's there

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