stay Python In the string of ,“\n” Means line break , Sometimes the output string happens to contain “\n” when , The output is different from the expected result , Pictured 1 Shown .
chart 1 The output string happens to contain “\n” when
chart 1 in , Intended to output “C:\some\name”, But at this time Python The interpreter will put the... In the string “\n” Look at line breaks , The output is not what we expected .
here , You can prefix the string with “r”, Indicates that the string is the original string , Pictured 2 Shown .
chart 2 Original string
among ,“r” yes “raw” namely “ original ” Abbreviation , here print() The function prints the string as it is , Not right “\n” Explain .
In use print() Function printing , If you need multiple lines to display the string , chart 3 The code shown will report an error .
chart 3 Multi line error code
among , The message is “ Wrong grammar ”. You can use three double quotes to enclose the string you want to display , At this point, you can perform multi line output , Pictured 4 Shown .
chart 4 Multiple lines of correct code
Two string literals arranged together can be automatically concatenated into a single string , Pictured 5 Shown .
chart 5 Auto connect string
among ,’Py’ and ’thon’ Are two string literals arranged together , here Python The interpreter automatically concatenates these two literals into a string . When automatically connecting strings , Single quotation marks and double quotation marks can be mixed , Pictured 6 Shown .
chart 6 A mixture of single and double quotation marks
here ,s1 and s2 The values are all “Python”.
It should be noted that , It must be a string literal to perform automatic connection , String variables cannot be automatically connected , Pictured 7 Shown .
chart 7 String variables cannot be automatically concatenated
among ,s1 and s2 The picture is 6 String defined in , At this time, the code reports an error , because s1 and s2 Is a string variable, not a string literal , So we can't put s1 and s2 Auto connect .