数据类型 字符串
一.python基本數(shù)據(jù)類型
1. 背景
面試題案例: 123和“123”一樣么?
- 從數(shù)字角度講
- 從程序語言的識別來講
>>> a = 123
>>> stra = "123"
>>> a == stra
False
>>> print a
123
>>> print stra
123
2.數(shù)字
(1)整型
>>> num1 = 123
>>> type(num1)
<type 'int'>
>>> type(123)
<type 'int'>
In [1]: num =1???
In [2]: type(num)
Out[2]: int? ####當輸入一個數(shù)時,默認為數(shù)據(jù)類型為整型
(2)長整形
In [3]: num =111111111111111111111111111111111111
In [4]: type(num)
Out[4]: long? ####當輸入一個數(shù)比較大時,默認為數(shù)據(jù)類型為長整型
In [5]: num =1
In [6]: type(num)
Out[6]: int
In [7]: num =1L? ###當輸入一個數(shù)后加了“L”時,強制定義為長整型
In [8]: type(num)
Out[8]: long
3.浮點型:表示小數(shù)
In [9]: a=12e9??
In [10]: print a
12000000000.0?? ####12e9 表示12成以10的九次方,類型時浮點型
In [11]: type(a)
Out[11]: float
4.復數(shù)類型:python對復數(shù)提供內(nèi)嵌支持,eg:3.14j, 8.32e-36j(幾乎用不到)
>>> c = 3.14
>>> type(c)
<type 'float'>
>>> c = 3.14j
>>> type(c)
<type 'complex'>
二 字符串類型
1.字符串的定義
# 字符串定義的第一種方式:
>>> str1 = 'our company is westos'
?
# 字符串定義的第二種方式:
>>> str2 = "our company is westos"
?
# 字符串定義的第三種方式:
>>> str3 = """our company iswestos"""
?
>>> type(str1)
<type 'str'>
>>> type(str2)
<type 'str'>
>>> type(str3)
<type 'str'>
?
2.轉(zhuǎn)義符號
一個反斜線加一個單一字符可以表示一個特殊字符,通常是不可打印的字符
\n: 代表換行符 \": 代表雙引號本身
\t: 代表tab符 \': 代表單引號本身
>>> say = 'let\'s go'>>> say??#####? \': 代表單引號本身
"let's go"
>>> say = "let's go "
>>> say
"let's go "
>>> mail = "tom: hello i am westos "
>>> print mail
tom: hello i am westos
>>> mail = "tom:\n hello\n i am westos "?? #####\n: 代表換行符
>>> print mail
tom:
hello
i am westos
In [13]: print '\hello\n'
\hello
In [14]: print 'hello\n'
hello??????? ####\n 表示換行
In [15]: print '\t hello\n'
??? hello?#####\t表示留出每行前面的幾個字符?? \t: 代表tab符
3.三重引號
塊注釋:多行代碼注釋
函數(shù)的doc文檔:講函數(shù)時會說到
字符串格式化
>>> mail = """tom:
...???? i am jack
...???? good luck
... """???????????? ####塊注釋
>>> print mail
tom:
??? i am jack
??? good luck
>>> mail
'tom:\n\ti am jack\n\tgood luck\n'
4.字符串操作預覽
字符串屬于序列,序列支持的操作如下:
索引 切片
判斷子串 重復
連接? 計算長度索引
(1)字符串索引
?索引(s[i] ):獲取特定偏移的元素。給出一個字符串,可輸出任意一個字符,如果索引為負數(shù),就是相當于從后向前數(shù)。
????????? 索引理解
字符串? h? e?l? l? o \n
索引?? 0? 1?2? 3? 4?5
索引? -6 -5 -4 -3-2 -1
>>> a = 'abcde'
>>> type(a)
<type 'str'>
>>> a[0]
'a'
>>> a[1]
'b'
>>> a[3]
'd'
>>> a[0]+a[1]
'ab'
>>> a[0]+a[2]
'ac'
In [16]: a='hello westos'
In [17]: a[1]?? ###給hello westos每個字符編號從0開始(包括空格),輸出第1個字符
Out[17]: 'e'
In [18]: a[6]?? ####輸出第6個字符
Out[18]: 'w'
(2)字符串切片
切片S[i:j]提取對應的部分作為一個序列:
上邊界并不包含在內(nèi);
如果沒有給出切片的邊界,切片的下邊界默認為0,上邊界為字符串的長度;
擴展的切片S[i:j:k],其中i,j含義同上,k為遞增步長;
s[:]獲取從偏移量為0到末尾之間的元素,是實現(xiàn)有效拷貝的一種方法
>>> a
'abcde'
>>> a[1:5:2]?????? //從第1至5個字符之間每隔兩個字母切取
'bd'
>>> a[1:5]??????? //代表切片取出第2個到第4個
'bcde'
>>> a[:5]???????? //從頭取
'abcde'
>>> a[4:]????????? //取到結(jié)尾
'e'
>>> a[4:1]??????????? //python中默認是從左向右取值
''
>>> a[4:1:-1]??????? //當步長為-1時,從右向左取值
'edc'
>>> a[:]'abcde'
>>> a[-1]
'e'
>>> a[-4:-1]??????? //代表倒數(shù)第2個到倒數(shù)第4個切片
'bcd'
>>> a[-2:-4]
''
>>> a[-2:-4:1]
''
>>> a[-2:-4:-1]
'dc
In [19]: a[0:5]? ####輸出從0到5 個字符
Out[19]: 'hello'
(3)判斷子符串
判斷一個sub字符串是不是屬于s字符串:
sub in s??? ####字符屬于s字符串
sub not in s ####字符不屬于s字符串
截圖:
(4)重復、連接及計算長度
In [7]: print '=='*10?? ######雙等號重復10遍
====================
In [8]: print 'hello'+'linux'? ####鏈接hello和linux
hellolinux???????
?
In [9]: s = 'linux'
In [10]: len(s)?? #####計算s的長度
Out[10]: 5
(5)字符串的類型轉(zhuǎn)換
str(obj) 將其他類型內(nèi)容轉(zhuǎn)換為字符串
int(obj) 將字符串轉(zhuǎn)換為為整數(shù)
float(obj) 將字符串轉(zhuǎn)換為浮點型
long(obj) 將字符串轉(zhuǎn)換為長整型
(6)字符串常用操作:
In [19]: s = 'westos'
In [20]: s. (+tab鍵)
s.capitalize? s.format????? s.isupper???? s.rindex????? s.strip
s.center????? s.index?????? s.join??????? s.rjust?????? s.swapcase
s.count?????? s.isalnum???? s.ljust?????? s.rpartition? s.title
s.decode????? s.isalpha???? s.lower?????? s.rsplit????? s.translate
s.encode????? s.isdigit???? s.lstrip????? s.rstrip????? s.upper
s.endswith??? s.islower???? s.partition?? s.split??????s.zfill
s.expandtabs? s.isspace???? s.replace???? s.splitlines??
s.find??????? s.istitle???? s.rfind?????? s.startswith?
?
####1. s.capitalize()- 將字符串首字母大寫,并返回新的首字母大寫后的字符串;
In [20]: s.capitalize()
Out[20]: 'Westos'
In [21]: help (s.capitalize)? ###查看s.capitalize()的用法
#####2. s.center(width[,fillchar])- 返回一個長為width的新字符串,在新字符串中原字符居中,其他部分用fillchar指定的符號填充,未指定時通過空格填充。
In [26]: s = "welcome"
In [27]: s.center(10,'*')? ####返回一個長為10的新字符串,其他部分用 '*' 填充
Out[27]: '*welcome**'
In [28]: s.center(20,'*')?? ####返回一個長為20的新字符串,其他部分用 '*' 填充
Out[28]: '******welcome*******'
In [29]: s.center(20)
Out[29]: '????? welcome?????? '??####返回一個長為20的新字符串,其他部分用空格填充
######3.str.count(sub[, start[, end]]) -> int- 返回sub在s中出現(xiàn)的次數(shù),如果start與end指定,則返回指定范圍內(nèi)的sub出現(xiàn)次數(shù)。
In [30]: s= "i like fentiao"
In [31]: s.count("i")?? #####整個"i like fentiao"中有幾個'i'
Out[31]: 3
In [32]: s.count("i",1)? #### 在" like fentiao"中有幾個'i'
Out[32]: 2
In [34]: s.count("i",1,5)? ####在" like"中有幾個'i'
Out[34]: 1
#######4. s.endswith(suffix[, start[, end]])- 判斷字符串是否以suffix結(jié)束,如果start和end指定,則返回str中指定范圍內(nèi)str子串是否以suffix結(jié)尾,如果是,返回True;否則返回False
In [35]: s= "i like fentiao"
In [36]: s.endswith('iao')?? #####字符串是否以iao結(jié)束
Out[36]: True
In [37]: s.endswith('iao',1,5)? #####在" like"中,字符串是否以iao結(jié)束,
Out[37]: False
In [38]: s.endswith('iao',1,20)? ####整個"i like fentiao"中,字符串是否以iao結(jié)束,
Out[38]: True
#######5. s.startswith(prefix[, start[, end]])- 判斷字符串是否以prefix開始,如果start和end指定,則返回s中指定范圍內(nèi)s子串是否以prefix結(jié)尾,如果是,返回True;否則返回False
In [39]: s.startswith('iao',1,5) #####在"like"中,字符串是否以iao開始
Out[39]: False
In [40]: s.startswith('i',0,5)? #####在"i like"中,字符串是否以i開始
Out[40]: True
####6.s.find(sub[,start[,end]]) - 判斷sub是否在s中,存在返回索引值,不存在返回-1.
In [41]: s= "i like fentiao"
In [43]: s.find('i')?? #####i是否在s中,存在返回索引值0
Out[43]: 0
In [44]: s.find('o')? #####o是否在s中,存在返回索引值13
Out[44]: 13
In [45]: s.find('u')? #####u是否在s中,不存在返回-1
Out[45]: -1
####7.s.index(sub[,start[,end]])- 與find方法函數(shù)功能相同,如果sub不存在時拋出ValueError異常;
In [41]: s= "i like fentiao"
In [46]: s.index('i',5,8)? #########i是否在5-8的字符中,不存在時拋出ValueError異常;
---------------------------------------------------------------------------
ValueError???????????????????????????????Traceback (most recent call last)
<ipython-input-46-1bbced859d67> in <module>()
----> 1 s.index('i',5,8)
ValueError: substring not found
In [47]: s.index('i',0,8)??? #########i是否在0-8的字符中,存在返回索引值0
Out[47]: 0
In [48]: s.index('i',1,20)?? #########i是否在1-20的字符中,存在,返回i的個數(shù)
Out[48]: 3
#######8.? s.isalnum() //判斷是否都是字母或數(shù)字
#######9.? s.isalpha() //判斷是否都是字母
#######10. s.isdigit() //判斷是否都是數(shù)字
#######11. s.islower() //判斷是否都是小寫
#######12. s.isspace() //判斷是否都是英文空格
#######13. s.istitle() //判斷是不是都是標題(有大小寫)
#######14. s.isupper() //判斷是不是都為大寫字母
#######15. s.join(seq)- 以s作為分隔符,將序列seq中的所有元素合并為一個新的字符串。
In [53]: s= 'hello'
In [54]: b="linux"
In [55]: s.join(b)? #####以hello作為分隔符,將序列l(wèi)inux中的所有元素合并為一個新的字符串
Out[55]: 'lhelloihellonhellouhellox'?###l hello i hello n hello u hello x?用hello將linux中的每個字符隔開
#######16. s.replace(old,new[,count])- 將s中的old字符串替換為new字符串,并將替換后的新字符串返回,如果count指定,則只替換前count個
In [60]: s= "i i like cat cat "
In [61]: s.replace("i","we")?? #####將s中的i字符串替換為we字符串,(全部)
Out[61]: 'we we lweke cat cat '
In [62]: s.replace("i","we",1) #####將s中的i字符串替換為we字符串,(替換前一個)
Out[62]: 'we i like cat cat '
#######17. s.split([sep[,maxsplit]])- 以sep字符串作為分割符對s進行切割,默認為空格;
????????????????????????????????????? -maxsplit代表切割的此處
In [73]: s = '172.25.254.144'
In [74]: s.split()? ###### 以空格作為分割符對s進行切割
Out[74]: ['172.25.254.144']
In [75]: s.split('.')###### 以'.'作為分割符對s進行切割
Out[75]: ['172', '25', '254', '144']
In [76]: s= "i like ww? qq"
In [77]: s.split()??? ###### 以空格作為分割符對s進行切割
Out[77]: ['i', 'like', 'ww', 'qq']
#######18. s.strip([chars]) -返回一字符串,將s中首尾包含指定的chars字符刪除的字符串,未指定時,刪除首尾的空格。
In [78]: s= "??? westo??? "????
In [79]: s.strip()? #####刪除首尾的空格。
Out[79]: 'westo'
In [80]: s.lstrip()? #####刪除首的空格。
Out[80]: 'westo??? '
In [81]: s.rstrip()?? #####刪除尾的空格。
Out[81]: '??? westo'
In [88]: s='oowwoo'
In [89]: s.rstrip('o')? #####刪除尾的o。
Out[89]: 'ooww'
In [90]: s.lstrip('o')? #####刪除首的o。
Out[90]: 'wwoo'
In [91]: s.strip('o')? #####刪除首尾的o。
Out[91]: 'ww'
(7)當s的定義類型不一樣,執(zhí)行的操作也不一樣;
截圖:
習題;
(1)判斷變量名是否合法:
代碼:
import? string
name = raw_input("changename: ")
if name[0] not in string.letters + "_":
??? print?"the first number is errot"
??? exit(0)
else:
??? for item in name[1:]:
??????? if item not instring.letters+"_"+string.digits:
??????????? print "changename iserror"
??????????? exit(0)
print "changename is error"
截圖:
(2)截圖:
第一問:
myint= raw_input("input english : ")#####輸入
myint1 = myint.split()???? ########### 以空格作為分割符對myint進行切割
print len(myint1)??????? #####myint1的長度
第二問:
myint= raw_input("input english : ") #####輸入
myint1 = myint.split()? ########### 以空格作為分割符對myint進行切割
myint2 = set (myint1) ####運用集合的知識
print len(myint1)? #####myint1的長度
print len(myint2)? #####myint2的長度
本文轉(zhuǎn)自 如何何如? 51CTO博客,原文鏈接:http://blog.51cto.com/12778805/1945040,如需轉(zhuǎn)載請自行聯(lián)系原作者
總結(jié)
- 上一篇: 电脑无故弹出yyy102.html网页的
- 下一篇: Spring+Quartz实现定时任务