简体   繁体   中英

What is the function of the second slash in a python print function. I know the first is an escape sequence but i dont understand why they have 2

here is the code:

print('Hello World\nIt\'s hot today')

okay I get the first slash is an escape sequence but whats the second slash for?

print('Hello World\nIt\'s hot today')

The 2nd slash here, which appears before a ' character, allows you to use this character in a string which is scoped with it (otherwise, the Python interpreter has to conclude that this character is where the string ends).

Alternatively, you could scope this string with " instead of ' , which would make that 2nd slash redundant:

print("Hello World\nIt's hot today")

The second \ is to escape ' . Without this, python would see

'Hello World\nIt's hot today'

Now, it would interpret 'Hello world\nIt' as a string, because you ended it with ' ! Then it does not know what to do with the rest of your code s hot today' , resulting in an syntax error.

To avoid escaping ' , you could instead use " :

print("Hello World\nIt's hot today")

The same goes for escaping " . If you want to print a string He said "Hello, world!" , then you would want either one of the following:

print("He said \"Hello, world!\"")
print('He said "Hello, world!"')

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