標籤:作用 使用 python log 變數 處理 last class input
一、單引號字串和轉義引號
當字串中出現單引號‘時,我們可以用雙引號""將該字串引起來:"Let‘s go!"
而當字串中出現雙引號時,我們可以用單引號‘‘將該字串引起來:‘ "Hello,world!" she said ‘
但是當字串中又有單引號‘又有雙引號"時該如何處理呢:使用反斜線(\)對字串中的引號進行轉義:‘Let\‘s go!‘
二、字串
- 拼接字串
>>>"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基礎文法——(引號、字串)