程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How to use strings in Python 2-1

編輯:Python

1 Original string

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 .

2 Multi line display string

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

3 Auto connect string

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved