Python基礎文法——(引號、字串)

來源:互聯網
上載者:User

標籤:作用   使用   python   log   變數   處理   last   class   input   

一、單引號字串和轉義引號

  當字串中出現單引號‘時,我們可以用雙引號""將該字串引起來:"Let‘s go!"

  而當字串中出現雙引號時,我們可以用單引號‘‘將該字串引起來:‘ "Hello,world!" she said ‘

  但是當字串中又有單引號‘又有雙引號"時該如何處理呢:使用反斜線(\)對字串中的引號進行轉義:‘Let\‘s go!‘

二、字串

  1. 拼接字串
>>>"Let‘s say"  ‘ "Hello,world!" ‘‘Let\‘s say "Hello,world!" ‘
>>>x="hello,"
>>>y="world!"
>>>x y
SyntaxError: invalid syntax
>>>"hello,"+"world!"
‘hello,world!‘
>>>x+y
‘hello,world!‘

   上面只是一個接著一個的方式寫了兩個字串,Python就會自動拼接它們,但是如果賦值給變數再用這種方式拼接則會報錯,因為這僅僅是書寫字串的一種特殊方法,並不是拼接字串的一般方法;這種機制用的不多。用"+"好可以進行字串的拼接;

  2.字串表示,str和repr

>>>print repr("hello,world!")‘hello,world!‘>>>print repr(10000L)10000L>>>print str("Hello,world!")Hello,world!>>>print str(10000L)10000

 str和int、bool一樣,是一種類型,而repr僅僅是函數,repr(x)也可以寫作`x`實現(注意,`是反引號,不是單引號);不過在Python3.0中已經不再使用反引號了。因此,即使在舊的代碼中應該堅持使用repr。

  3.input和raw_input的比較

  input會假設使用者輸入的是合法的Python運算式,比如輸入數值1,程式不會當作是str,而是當作int類型,輸入x,程式會當作使用者輸入的是變數x,如果輸入"x",程式才會人可是字串;

  raw_input函數它會把所有的輸入當作未經處理資料,然後將其放入字串中。

>>> name=input("what is your name ?");print namewhat is your name ?AllenTraceback (most recent call last):  File "<pyshell#22>", line 1, in <module>    name=input("what is your name ?");print name  File "<string>", line 1, in <module>NameError: name ‘Allen‘ is not defined>>> name=input("what is your name ?");print namewhat is your name ?"Allen"Allen>>>input("Enter a number:")Enter a number:33>>>raw_input("Enter a number:")Enter a number:3‘3‘

 

Python基礎文法——(引號、字串)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.