Charles
Charles

Reputation: 479

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.

Upvotes: 1

Views: 560

Answers (3)

PROTOCOL
PROTOCOL

Reputation: 371

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

Upvotes: 0

redratear
redratear

Reputation: 249

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 "\"...

Upvotes: 2

Yu Hao
Yu Hao

Reputation: 122493

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

Upvotes: 3

Related Questions