1. 程式人生 > >Python基礎語法——(引號、字符串)

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

數值 就會 str 斜線 inpu 數據 自動 兩個 raw

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

  當字符串中出現單引號‘時,我們可以用雙引號""將該字符串引起來:"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 name
what is your name ?Allen

Traceback (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 name
what is your name ?"Allen"
Allen

>>>input("Enter a number:")
Enter a number:3
3
>>>raw_input("Enter a number:")
Enter a number:3
‘3‘

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