在Python中,萬物皆對象,顯然字符串是對象類型,用str表示。字符串類型一般用單引號或者雙引號包裹起來。javascript
>>> "Hello,world" 'Hello,world' >>> 'Hello,world' 'Hello,world' >>> type("Hello,world") <type 'str'> >>>
在Python中變量無類型,對象有類型html
>>> b = "hello,world" >>> b 'hello,world' >>> print b hello,world >>> type(b) <type 'str'>
>>> "py" + "thon" 'python' >>> >>> a = 1989 >>> b = "free" >>> print a + b Traceback (most recent call last): File "<pyshell#195>", line 1, in <module> print a + b TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> print b + `a` #反引號將整數a轉化爲字符串 free1989 >>>
用「+」拼接起來的字符串的兩個對象必須是同一類型的。若是是數字則是求和,若是是字符串則獲得一個新的字符串。html5
還有其餘兩種方法能夠將整數轉化爲字符串:java
str():將整數對象轉換爲字符串對象python
>>> print b + str(a) free1989
repr():至關於反引號``c++
>>> print b + repr(a) free1989
int():將字符串對象轉換爲整數對象git
>>> a = "250" >>> b = int(a) >>> b 250 >>> type(b) <type 'int'> >>>
在字符串中,總會有一些特殊的符號,就須要用轉義符。所謂轉義,就是不採用符號原本的含義,而採用另一含義。下面表格中列出經常使用的轉義符:shell
轉義字符 | 描述 |
---|---|
\ | (在行尾時) 續行符 |
\ | 反斜槓符號 |
' | 單引號 |
" | 雙引號 |
a | 響鈴 |
b | 退格(Backspace) |
e | 轉義 |
000 | 空 |
n | 換行 |
v | 縱向製表符 |
t | 橫向製表符 |
r | 回車 |
f | 換頁 |
oyy | 八進制數,yy表明的字符,例如:o12表明換行 |
xyy | 十六進制數,yy表明的字符,例如:x0a表明換行 |
other | 其它的字符以普通格式輸出 |
用轉義符可以讓字符串中的某些符號表示原來的含義,而不是被解析成某種具備特別能力的符號。下面看看這個代碼:api
>>> dos = "c:\news" >>> dos 'c:\news' >>> print dos #當用print打印時就出現問題了 c: ews
如何避免上述代碼的問題?有兩種方法,其一是前面介紹的轉義符解決。數組
>>> dos = "c:\\news" >>> print dos c:\news >>>
其二是聲明爲原始字符串
>>> dos = r"c:\news" >>> print dos c:\news >>> dos = r"c:\news\python" >>> print dos c:\news\python
如r"c:news"
,由r開頭引發的字符串就是聲明瞭後面引號裏的東西是原始字符串,在裏面聽任何字符都表示該字符的原始含義,不須要再用轉義符了。
下面實現接收和打印用戶經過鍵盤輸入的內容:
不過在寫這個功能前,要了解函數:
Python 2:raw_input()
Python 3: input()
這是Python的內建函數(built-in function)。關於內建函數,能夠分別經過下面的連接查看:
關於Python的內建函數,下面列出來,供參考:
abs() divmod() input() open() staticmethod() all() enumerate() int() ord() str() any() eval() isinstance() pow() sum() basestring() execfile() issubclass() print() super() bin() file() iter() property() tuple() bool() filter() len() range() type() bytearray() float() list() raw_input() unichr() callable() format() locals() reduce() unicode() chr() frozenset() long() reload() vars() classmethod() getattr() map() repr() xrange() cmp() globals() max() reversed() zip() compile() hasattr() memoryview() round() __import__() complex() hash() min() set() delattr() help() next() setattr() dict() hex() object() slice() dir() id() oct() sorted()
怎麼才能知道哪一個函數怎麼用,而且用來幹什麼的呢?
help(abs)命令
raw_input
>>> raw_input("input your name: ") input your name: michael 'michael' >>> name = raw_input("input your name: ") input your name: michael >>> name 'michael' >>> type name SyntaxError: invalid syntax >>> type(name) <type 'str'> >>> age = raw_input("How old are you? "); How old are you? 25 #輸入數字 >>> age '25' >>> type(age) <type 'str'> #返回還是str類型
>>> print "Hello, world" Hello, world >>> a = "python" >>> print a python >>> b = "good" >>> print a,b python good >>>
特別提醒的是,print的返回值默認是以n
結尾的,因此每一個輸出語句以後自動換行。
在Python中,把像字符串這樣的對象類型統稱爲序列,顧名思義,序列就是有序排列。在這個序列中,每一個人都有編號,編號和每一個字符一一對應,在Python中這些編號稱爲索引。
>>> lang = "study python" >>> lang[0] 's' >>> lang[1] 't'
也能夠這樣作:
>>> "study python"[0] 's' >>> "study python"[1] 't' >>>
經過字符找到其在字符串中的索引值:
>>> lang = "study python" >>> lang.index("p") 6 >>> lang.in SyntaxError: invalid syntax >>> lang.index("y") 4
不論是獲得一個字符仍是多個字符,經過索引獲得字符的過程稱爲切片。
>>> lang = "study python" >>> lang[2:9] #獲得從2號到9號之間的字符串(包括2號但不包括9號) 'udy pyt' >>> b = lang[1:] #獲得從1號到最末尾的字符 >>> b 'tudy python' >>> c = lang[:] #獲得全部的字符 >>> c 'study python' >>> d = lang[:10] #獲得從0到10號以前的字符 >>> d 'study pyth' >>> lang[1:12] 'tudy python' >>> lang[0:13] #若是第二個數字的長度大於字符串的長度,獲得的返回結果就自動到最大長度終止,可是這種得到切片的方法是值得提倡的。特別是若是在循環中,這樣作極可能會遇到麻煩。 'study python' >>> lang[0:14] 'study python
若是在切片的時候,冒號左右都不寫數字,就是前面所操做的c = lang[:]
,其結果是變量的值c與源字符串lang同樣,即複製了一份,那是否是真的複製呢?下面的方式檢驗一下:
>>> id(c) 44841944 >>> id(lang) 44841944
從上面能夠看出,兩個內存地址同樣,說明c和lang兩個變量指向的是同一個對象。用c = lang[:]
的方式並無生成一個新的字符串,而是將變量c這個標籤頁貼在原來那個字符串上了。
>>> lang = "study python" >>> c = lang >>> id(c) 50456160 >>> id(lang) 50456160
上述這種狀況,變量c和lang也指向同一個對象。
全部序列都有以下操做,字符串是序列的子集。
len():返回序列長度
+:鏈接兩個序列
*:重複序列元素
in: 判斷元素是否存在於序列中
max():返回最大值
min():返回最小值
cmp(str1,str2): 比較兩個序列值是否相同
>>> str1 = "study" >>> str2 = "python" >>> str1 + str2 'studypython' >>> str1 + "-->" + str2 'study-->python'
in用來判斷某個字符串是否是在另一個字符串內,或者判斷某個字符串內是否包含某個字符串,包含則返回True,不然返回false。
>>> str = "study python" >>> "s" in str True >>> "i" in str False >>> "su" in str False >>> "stu" in str True >>>
str = "python"
max(str)
'y'
>>> str = "python" 'y' >>> min(str) 'h'
將兩個字符串進行比較,首先將字符串中的符號轉化爲對應的數字,而後再比較
若是返回的數值小於0,說明前者小於後者
等於0,表示二者相等
大於0,表示前者大於後者
>>> cmp("aaa","abc") # -1 >>> cmp("abc","aaa"); 1 >>> cmp("abc","abc"); 0
>>> ord("a") #返回字符的ASCII值 97 >>> chr(97) #返回ASCII值所對應的字符 'a'
以指定的次數重複打印字符串
>>> str = "python" >>> str * 4 'pythonpythonpythonpython' >>> print "-" * 20 --------------------
len()返回字符串的長度,返回值類型是int型
>>> a = "hello" >>> m = len(a) >>> m 5 >>> type(m) <type 'int'> >>>
字符串的方法有不少,能夠經過dir來查看:
>>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> "python".isalpha() #字符串全是字母,返回TRUE True >>> "2python".isalpha() #字符串含有非字母,返回FALSE False >>>
split()做用是將字符串根據某個分隔符進行分割。
>>> str = "I love Beijing" >>> str.split(" ") ['I', 'love', 'Beijing'] #返回值爲名叫列表(list)的類型 >>> str = "www.baidu.com" >>> str.split(",") ['www', 'baidu', 'com'] >>>
>>> str = " python " >>> str.strip() #去掉字符串左右空格 'python' >>> str.lstrip() #去掉字符串左邊空格 'python ' >>> str.rstrip() #去掉字符串右邊空格 ' python' >>>
>>> str = "pyThon" >>> str.upper() #將小寫字母徹底變爲大寫字母 'PYTHON' >>> str.lower() #將大寫字母徹底變成小寫字母 'python' >>> str.isupper() #判斷是否全是大寫字母 False >>> str.islower() #判斷是否全是小寫字母 False >>> str = "this is book" >>> str.capitalize() #把全部單詞的第一個字母轉化爲小寫字母 'This is book' >>> str.istitle() #判斷每一個單詞的第一個字母是否爲大寫字母 False >>>
>>> b = "www.baidu.com" >>> c = b.split(".") >>> c ['www', 'baidu', 'com'] >>> ".".join(c) 'www.baidu.com' >>> "**".join(c) 'www**baidu**com'
>>> "I like %s" % "Python" #%s表示字符串 'I like Python' >>> "%d years old" % 25 #%d表示整數 '25 years old' "I like 'python'" >>> "%s is %d years old" % ("deason",25) 'deason is 25 years old'
%s 字符串(採用str()的顯示)
%r 字符串(採用repr()的顯示)
%c 單個字符
%b 二進制整數
%d 十進制整數
%e 指數(底數爲e)
%f 浮點數
{}做爲佔位符
>>> str = "I like {}".format("python"); >>> str 'I like python' >>> str = "{0} is {1} years old".format("michael",25) >>> str 'michael is 25 years old'
>>> lang = "python" >>> print "I love %(program)s" %{"program":lang} I love python >>> print "I love %(program)s" %{"program":"python"} I love python
綜上,推薦使用:string.format()
此前已經知道了Python的三種對象類型:int、float和str。下面開始學習一種新的Python對象類型:list。list在Python中具備很是強大的功能。
在Python中,用方括號表示一個list:[],方括號裏面的元素類型,能夠是int型數據,也能夠是str類型的數據,甚至也能夠是bool類型數據。而像Java語言,數組裏面只能存在一種類型的數據。
>>> a=[] #定義了一個空的列表,變量a至關於一個貼在其上的標籤 >>> type(a) #用內置函數type()查看變量a引用對象的類型,爲list <type 'list'> >>> bool(a) #用內置函數bool()查看a的布爾值,由於是空,因此爲False False >>> print a []
下面看看list具體的使用
>>> a=['a',3,'hello',True] #list中能夠有多中數據類型 >>> a ['a', 3, 'hello', True] >>> type(a) <type 'list'> >>> bool(a) True >>> print a ['a', 3, 'hello', True] >>> a[3] True >>> type(a[3]) <type 'bool'>
和字符串中的索引相似,只不過list是以元素爲單位,而不是以字符爲單位進行索引。
>>> a=[2,3,True,"Hello,world"] >>> a [2, 3, True, 'Hello,world'] >>> a[0] 2 >>> a[1] 3 >>> a[2] True >>> a[3] 'Hello,world' >>> type(a[0]) <type 'int'> >>> type(a[2]) <type 'bool'> >>> type(a[3]) <type 'str'> >>> a.index(2) 0 >>> a.index(3) 1 >>> a.index(True) 2 >>> a.index("Hello,world") 3 >>>
>>> lst = ['python','java','c++'] >>> lst[-1] 'c++' >>> lst[-3:-1] ['python', 'java'] >>> lst[-1:-3] [] >>> lst[0:3] ['python', 'java', 'c++'] >>>
序列的切片,必定要左邊的數字小於右邊的數字,lst[-1:-3]就沒有遵照這個規則,返回的是一個空。
>>> mList = [1,2,3,4,5,6] >>> mList[::-1] [6, 5, 4, 3, 2, 1] >>> m >>> mList [1, 2, 3, 4, 5, 6] >>>
固然,也能夠對字符串進行反轉:
>>> lang="python" >>> lang[::-1] 'nohtyp' >>> lang 'python'
能夠看出,不論是str仍是list,反轉以後原來的值沒有改變。這說明,這裏的反轉不是把原來的值倒過來,而是新生成了一個值,生成的值跟原來的值相比是倒過來的。
Python還有一種方法使list反轉,且比較容易閱讀和理解,特別推薦:
mList = [1,2,3,4,5,5,6,8,7] >>> list(reversed(mList)) [7, 8, 6, 5, 5, 4, 3, 2, 1] >>> s='abcd' >>> list(reversed(s)) ['d', 'c', 'b', 'a'] 'abcd'
>>> lst=['python','java','c++'] >>> len(lst) 3
>>> lst=['python','java','c++'] >>> lst ['python', 'java', 'c++'] >>> alst =[1,2,3,4,5] >>> lst + alst ['python', 'java', 'c++', 1, 2, 3, 4, 5]
>>> lst * 3 ['python', 'java', 'c++', 'python', 'java', 'c++', 'python', 'java', 'c++']
>>> 'python' in lst True
>>> max(alst) 5 >>> min(alst) 1 >>> max(lst) 'python' >>> min(lst) 'c++'
>>> a = [2,3] >>> b = [2,4] >>> cmp(a,b) -1 >>> cmp(b,a) 1 >>> c=[2] >>> cmp(a,c) 1 >>> d=['2'] >>> cmp(a,d) -1
>>> lst ['python', 'java', 'c++'] >>> lst.append("html5") #將元素追加到list的尾部 >>> lst ['python', 'java', 'c++', 'html5'] >>> lst.append(100) >>> lst ['python', 'java', 'c++', 'html5', 100]
等價於:
>>> lst ['python', 'java', 'c++', 'html5', 100] >>> lst[len(lst):] = [3] >>> lst ['python', 'java', 'c++', 'html5', 100, 3] >>> len(lst) 6 >>> lst[6:]=['javascript'] >>> lst ['python', 'java', 'c++', 'html5', 100, 3, 'javascript']
list是Python中的苦力,那麼它都有哪些函數呢?
>>> dir(list) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
先無論以雙下劃線開始和結尾的函數,就剩下如下幾個
'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'
list.append(x),是將某個元素x添加到已知的一個列表的尾部。
list.extend(L),則是將兩個列表合併,或者說將列表L追加到列表list中。
>>> a=[1,2,3] >>> b=["lau",3,4,5] >>> a.extend(b) >>> a [1, 2, 3, 'lau', 3, 4, 5] >>> b ['lau', 3, 4, 5]
>>> a=[1,2,3] >>> b="abc" >>> a.extend(b) >>> a [1, 2, 3, 'a', 'b', 'c'] >>> c = 5 >>> a.extend(c) Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> a.extend(c) TypeError: 'int' object is not iterable
若是extend的參數對象是數值型則報錯。
因此,extend的參數對象是一個list,若是是str,則Python會先把它按照字符爲單位轉化爲list再添加到目標list中。官方文檔指出extend的元素對象必須是iterable(可迭代的)。
判斷一個對象是否是可迭代的?
>>> s="python" >>> hasattr(s,'__iter__') False >>> a=[1,2,3] >>> hasattr(a,'__iter__') True
經過內建函數hasattr()判斷一個對象是否是可迭代的,它的判斷本質就是看那個類型中是否有__iter__
函數。
append和extend函數的相同點
>>> a=[1,2,3] >>> b=[4,5,6] >>> id(a) 49822856 >>> id(b) 50066536 >>> a.extend(b) >>> a [1, 2, 3, 4, 5, 6] >>> id(a) 49822856
>>> a=[1,2,3] >>> id(a) 50068376 >>> a.append(12) >>> a [1, 2, 3, 12] >>> id(a) 50068376
由上面兩段代碼可知,append和extend函數的共同點:
都是原地址修改列表,不會建立一個新的列表
沒有返回值
append和extend函數的不一樣點
>>> lst=[1,2,3] >>> lst.append(["python","java"]) >>> lst [1, 2, 3, ['python', 'java']] >>> len(lst) 4 >>> >>> lst2=[1,2,3] >>> lst2.extend(["python","java"]) >>> lst2 [1, 2, 3, 'python', 'java'] >>> len(lst2) 5
可知,append是總體的追加,extend是單個的追加
count的做用是計算某個元素在該list中出現的次數
>>> a=[1,2,1,1,1] >>> a.count(1) 4 >>> a.append('a') >>> a.append('a') >>> a [1, 2, 1, 1, 1, 'a', 'a'] >>> a.count('a') 2 >>> a.count(4) #不存在,則返回爲0 0
index計算元素在該列表首次出現的位置
>>> a=[1,2,3,4,4,5] >>> a.index(4) 3 >>> a.index(6) #若是不存,就報錯 Traceback (most recent call last): File "<pyshell#85>", line 1, in <module> a.index(6) ValueError: 6 is not in list
list.insert(i,x),想列表中指定的位置插入元素x。
>>> a=[1,2,3,4,5] >>> a.insert(0,0) >>> a [0, 1, 2, 3, 4, 5] >>> a.insert(3,7) >>> a [0, 1, 2, 7, 3, 4, 5] >>> a.insert(8,4) #若超出列表長度,則將元素插入到列表末尾 >>> a [0, 1, 2, 7, 3, 4, 5, 4]
刪除列表中元素的方法有兩個,分別是:
list.remove(x)
刪除列表中首次出現的元素x,若是不存在元素x,則報錯
>>> a [0, 1, 2, 7, 3, 4, 5, 4] >>> a.remove(4) >>> a [0, 1, 2, 7, 3, 5, 4] >>> a.remove(6) Traceback (most recent call last): File "<pyshell#103>", line 1, in <module> a.remove(6) ValueError: list.remove(x): x not in list
list.pop([i])
刪除列表中位置i的元素而且返回該元素。若是沒有指定位置i,則默認刪除並返回列表的最後一個元素。
>>> a.pop(0) #刪除指定位置0 0 >>> a [1, 2, 7, 3, 5, 4] >>> a.pop() #刪除默認位置 4 >>> a [1, 2, 7, 3, 5] >>> a.pop(5) #超過列表長度則會報錯 Traceback (most recent call last): File "<pyshell#116>", line 1, in <module> a.pop(5) IndexError: pop index out of range
將列表的元素順序反過來,不會建立新的列表,所以沒有返回值
>>> a=[1,2,3,4,5,6,7] >>> a.reverse() >>> a [7, 6, 5, 4, 3, 2, 1] >>> a=['ss','aaa','dd'] >>> a.reverse() >>> a ['dd', 'aaa', 'ss']
sort是對列表進行排序,不會建立新的列表,所以沒有返回值
>>> a=[1,3,9,7,5] >>> a.sort() #默認從小到大的排序 >>> a [1, 3, 5, 7, 9] >>> a.sort(reverse = True) #從大到小的排序 >>> a [9, 7, 5, 3, 1]
>>> lst=["python","java","c","basic","ruby"] >>> lst.sort(key=len) #以字符串長度爲關鍵詞進行排序 >>> lst ['c', 'java', 'ruby', 'basic', 'python']
都屬於序列,所以那些屬於序列的操做對二者都適用
最大區別是,列表自身能夠改變,字符串自身不能夠改變
字符串只能經過建立一個新的str來改變,新的str不是原來的字符串對象
在字符串中,每一個元素只能是字符
在列表中,每一個元素能夠是任何類型
>>> matrix=[[1,2,3],[4,5,6],[7,8,9]] >>> type(matrix) <type 'list'> >>> matrix[0][1] 2 >>> matrix[0] [1, 2, 3]
>>> line="hello I am good" >>> line.split(" ") ['hello', 'I', 'am', 'good'] >>> a = line.split(" ") >>> a ['hello', 'I', 'am', 'good'] >>> type(a) <type 'list'>
>>> a ['hello', 'I', 'am', 'good'] >>> type(a) <type 'list'> >>> " ".join(a) 'hello I am good'
元組(tuple)是用圓括號括起來的,元素之間用逗號隔開。
>>> t = 123,'abc',["come","here"] >>> t (123, 'abc', ['come', 'here']) >>> type(t) <type 'tuple'>
元組也是一種序列,這一點與列表、字符串相似。有如下特色:
元組其中的元素不能更改,和字符串相似
元組中的元素能夠是任何類型的數據,和列表相似
元組的索引和切片的基本操做和字符串、列表是同樣的。
>>> t (123, 'abc', ['come', 'here']) >>> t[2] ['come', 'here'] >>> t[1:] ('abc', ['come', 'here']) >>> t[2][0] 'come'
特別注意:若是一個元組中只有一個元素,應該在該元素後面加上一個半角的英文逗號:
>>> a=(3) >>> type(a) <type 'int'> >>> a=(3,) #加了逗號就是元組 >>> type(a) <type 'tuple'>
列表和元組之間能夠實現轉換,分別使用list()和tuple()
>>> t (123, 'abc', ['come', 'here']) >>> tlst = list(t) # tuple--->list >>> tlst [123, 'abc', ['come', 'here']] >>> type(tlst) <type 'list'> >>> >>> t_tuple = tuple(tlst) #list--->tuple >>> t_tuple (123, 'abc', ['come', 'here']) >>> type(t_tuple) <type 'tuple'>
元組比列表操做速度快。若是定義了一個值的常量集,而且惟一要用它作的是不斷地遍歷它,請使用元組代替列表
若是對不須要修改的數據進行「寫保護」,可使代碼更安全,這時使用元組而不是列表。若是必需要改變這些值,則須要執行元組到列表的轉換。
元組能夠在字典中被用做key,可是列表不行。由於字典的key必須是不可變的,元組自己是不可變的。
元組能夠用在字符串格式化中。