python基础2
####转义符号####
一个反斜线加一个单一字符可以表示一个特殊字符,通常是不可打印的字符
\n: 代表换行符 \": 代表双引号本身
\t: 代表tab符 \': 代表单引号本身
In [1]: print 'let's go' ###要将's转义###
File "<ipython-input-1-1f59d2736eda>", line 1
print 'let's go'
^
SyntaxError: invalid syntax
In [2]: print 'let\'s go'
let's go
###字符串定义####
1 单引号
In [3]: str1 = "hello"
In [4]: type(str1)
Out[4]: str
2 双引号
In [5]: srt2 = 'hello'
In [7]: type(srt2)
Out[7]: str
3 三个双引号
In [8]: str3 = """hello"""
In [9]: type(str3)
Out[9]: str
###字符串切片###
>>> s = 'hello'
>>> s[2:5]
'llo'
>>> s[0:5]
'hello'
>>> s[3:]
'lo'
>>> s[:3]
'hel'
>>> s[0:3:2]
'hl'
>>>
如果只有[:],则表示全部
####字符串常用操作####
In [1]: s = 'hello'
In [2]: type(s)
Out[2]: str
In [4]: s.
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
In [4]: s.capitalize() ###将第一个转换成大写字母###
Out[4]: 'Hello'
In [5]: help (s.capitalize) ###查看帮助,按q退出###
In [6]: help(s.c)
s.capitalize s.center s.count
In [6]: help(s.center) ###给一个宽度,如果字符串小于该宽度,就会自动填充,默认使用空格,如果传递的参数,除了数字还有字符,则会使用该字符填充,返回值为srt
例:
In [16]: s.center(10,'#')
Out[16]: '##hello###'
In [17]: s.center(10)
Out[17]: ' hello '
In [18]:
In [18]: s.
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
In [18]: "WORD".isupper() ###判断是否为大写,返回值为bool类型
Out[18]: True
In [19]: "2l".isalnum() ###数字和字母###
Out[19]: True ###返回bool值为true####
In [20]: "2l-".isalnum()
Out[20]: False
In [23]: "Wojfh".isalpha() ###字母###
Out[23]: True
In [24]: "234".isdigit() ###数字###
Out[24]: True
In [25]: "ldsjfkai".islower() ###小写字母###
Out[25]: True
In [26]: " ".isspace() ###空格###
Out[26]: True
In [27]: " d ".isspace()
Out[27]: False
In [28]: "Heloo".istitle() ###开头为大子字母###
Out[28]: True
In [29]: help(s.isupper) ###查看帮助###
Help on built-in function isupper:
In [29]:isupper(...)
S.isupper() -> bool
Return True if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
(END)
####导入模块srting###
srting.digits
string.letters
In [33]: import string
In [34]: string.digits
Out[34]: '0123456789'
In [35]: string.letters
Out[35]: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
编写程序:判断输入的字符串是否符合变量的规则
程序1:
import string
print "欢迎进入变量名检测系统".center(50,'*')
letter = raw_input("please input letters:")
if letter[0] in string.letters + '_':
n = 1
for letter1 in letter[1:]:
if letter1 in string.letters + string.digits + "_":
n +=1
if n == len(letter):
print "输入合法"
else:
print "输入的变量不合法"
else:
print "变量的第一个字符只能是字母或者下划线"
执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/untitled/1.py
********欢迎进入变量名检测系统*********
please input letters:sfak
输入合法
Process finished with exit code 0
/usr/bin/python2.7 /home/kiosk/PycharmProjects/untitled/1.py
please input letters:5kdgl
变量的第一个字符只能是字母或者下划线
Process finished with exit code 0
程序2:
import string
alphas = string.letters
nums = string.digits
print "欢迎进入变量检测系统V1.0".center(50,"*")
print 'Test string must be at least 1 char long'
variable = raw_input("输入检测的变量名:")
if len(variable) > 0:
if variable[0] not in alphas:
print '变量名必须为字母或下划线开头'
else:
for ochar in variable[1:]:
if ochar not in alphas + nums:
print '无效的变量名'
exit(1)
print '%s 变量名合法' % variable
else:
print '变量名长度必须大于0'
###字符串的常用操作###
In [48]: s = " hello "
In [49]: s.strip() ###屏蔽前后的空格###
Out[49]: 'hello'
In [50]: s.lstrip() ###屏蔽左边的空格###
Out[50]: 'hello '
In [51]: s.rstrip() ###屏蔽右边的空格###
Out[51]: ' hello'
In [52]: s = "hel lo" ###中间的空格不能屏蔽###
In [54]: s.strip()
Out[54]: 'hel lo'
In [56]: ip = "172.25.254.12"
In [57]: ip.split('.') ###指定分隔符为".",默认为空格,返回的是一个列表###
Out[57]: ['172', '25', '254', '12']
In [59]: "user1:x:1001:1001::/home/user1:/bin/bash".split(":")
Out[59]: ['user1', 'x', '1001', '1001', '', '/home/user1', '/bin/bash']
In [61]: "user1:x:1001:1001::/home/user1:/bin/bash".endswith("bash") ###以bash结尾###
Out[61]: True
In [62]: "user1:x:1001:1001::/home/user1:/bin/bash".startswith("user1") ###以user1开头###
Out[62]: True
In [63]: s.lower() ###转换成小写字母###
Out[63]: 'hel lo'
In [64]: s.upper() ###转换成大写字母###
Out[64]: 'HEL LO'
In [65]: s = 'hElO'
In [66]: s.swapcase() ###将大写转换成小写,小写转换成大写###
Out[66]: 'HeLo'
练习:要求用户输入一个英文句子,统计该英文句子中含有单词的数目
测试:输入:i like python very much
输出:5
a = raw_input("请输入一个英文句子:")
lengthen = len(a.split()) ###字符串计算长度:len()可以计算长度###
print lengthen
测试:
请输入一个英文句子:i like python very much
5
###字符串的重复,连接,计算长度###
In [76]: print "===="*10
========================================
In [77]: print "hello"+"work=ld"
hellowork=ld
In [78]: s = 'hello world'
In [79]: len(s)
Out[79]: 11
###字符串的常用操作###
In [92]: s
Out[92]: 'hello world'
In [93]: s.find('o') ###判断'o'是否在str中,存在返回第一个出现的索引值,不存在返回-1.
Out[93]: 4
In [94]: s.find('p')
Out[94]: -1
In [96]: s.index('e')
Out[96]: 1
In [97]: s.index('o') ###判断是否在str中,存在返回索引值,不存在就报错时抛出ValueError异常###
Out[97]: 4
In [98]: s.index('p')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-98-e5567af6b163> in <module>()
----> 1 s.index('p')
ValueError: substring not found
In [99]:
In [105]: s
Out[105]: '#####'
In [106]: s.join("hello world") ###以str作为分隔符,将序列“hello world”中的所有元素合并为一个新的字符串###
Out[106]: 'h#####e#####l#####l#####o##### #####w#####o#####r#####l#####d'
######str.replace(old,new[,count])
- 将str中的old字符串替换为new字符串,并将替换后的新字符串返回,如果count指定,则只替换前count个字符串######
In [108]: s = "westos"
In [109]: s = "westos linux"
In [110]: s.replace("wes","HAHAHA")
Out[110]: 'HAHAHAtos linux'
In [113]: S = "WWWWestos linux"
In [116]: S.replace("W","HE",3)
Out[116]: 'HEHEHEWestos linux'
#####列表#####
列表中的元素可以是任意类型,列表,字符串均可
In [67]: li = [] ###定义一个空列表###
In [68]: type(li)
Out[68]: list
In [70]: li = ["fentiao",5, "male"] ###列表中的元素可以是任意类型,列表,字符串,数字均可
####列表的索引与切片###
In [71]: li[1] ###索引###
Out[71]: 5
In [73]: li[0]
Out[73]: 'fentiao'
In [74]: li[2]
Out[74]: 'male'
In [75]: li[0:2] ###切片###
Out[75]: ['fentiao', 5]
In [76]: li[:] ###全部###
Out[76]: ['fentiao', 5, 'male']
In [77]: li
Out[77]: ['fentiao', 5, 'male']
In [78]: len(li) ###查看几个元素###
Out[78]: 3
In [79]: "fentiao" in li ###查看fentiao是否在li列表中###
Out[79]: True
In [80]: "fendai" in li
Out[80]: False
In [81]: li1 = [1,2,3]+[2,3,4] ###连接两个列表###
In [82]: print li1
[1, 2, 3, 2, 3, 4]
In [83]: li3 = li*3 ###重复三次###
In [84]: print li3
['fentiao', 5, 'male', 'fentiao', 5, 'male', 'fentiao', 5, 'male']
In [85]: li = ['fentiao',7,'male',['westos','redhat','linux']] ###列表中可以在嵌套列表###
In [86]: li[3][2] ###查询列表中的列表的元素##
Out[86]: 'linux'
In [87]: li[3]
Out[87]: ['westos', 'redhat', 'linux']
In [88]: li.
li.append li.extend li.insert li.remove li.sort
li.count li.index li.pop li.reverse
In [89]: li.append("hello") ###在列表中添加hello,默认添加在末尾###
In [90]: print li
['fentiao', 7, 'male', ['westos', 'redhat', 'linux'], 'hello']
In [91]: li.insert(0,'hel') ###在索引0前添加hel###
In [92]: print li
['hel', 'fentiao', 7, 'male', ['westos', 'redhat', 'linux'], 'hello']
In [93]: li.
li.append li.extend li.insert li.remove li.sort
li.count li.index li.pop li.reverse
In [93]: help(li.extend)
In [94]:
In [95]: li.extend('hel') ###添加多个元素###
In [96]: li
Out[96]:
['hel',
'fentiao',
7,
'male',
['westos', 'redhat', 'linux'],
'hello',
'h',
'e',
'l']
In [97]: li = ['hwllo',2,3,'hao']
In [98]: li
Out[98]: ['hwllo', 2, 3, 'hao']
In [99]: li.extend(['hello','world']) ###将hello,world,添加到列表中###
In [100]: li
Out[100]: ['hwllo', 2, 3, 'hao', 'hello', 'world']
In [101]: li[0]
Out[101]: 'hwllo'
In [102]: li[0] = 'fentiao' ###列表中的元素是可变的,因此可修改列表中的元素,直接赋值,###
In [103]: li
Out[103]: ['fentiao', 2, 3, 'hao', 'hello', 'world']
In [104]: li.count('hao') ###统计hao出现的次数###
Out[104]: 1
In [105]: li.count('fentiao')
Out[105]: 1
In [106]: li.count('fendai')
Out[106]: 0
In [107]: li.insert(2,'hello')
In [108]: li
Out[108]: ['fentiao', 2, 'hello', 3, 'hao', 'hello', 'world']
In [109]: li.count('hello')
Out[109]: 2
In [110]: li.index('fentiao') ###查看fentiao的索引###
Out[110]: 0
In [111]: li.index(2)
Out[111]: 1
In [113]: li.index('hello')
Out[113]: 2
In [114]: li.re
li.remove li.reverse
In [114]: li.remove("hello") ###删除hello###
In [115]: li
Out[115]: ['fentiao', 2, 3, 'hao', 'hello', 'world']
In [116]: li.remove(li[3]) ###删除li[3]对应的元素###
In [117]: li
Out[117]: ['fentiao', 2, 3, 'hello', 'world']
In [118]: li.pop() ###弹出,默认弹出最后一个###
Out[118]: 'world'
In [119]: li.pop(3) ###弹出索引为3的元素###
Out[119]: 'hello'
In [120]: li
Out[120]: ['fentiao', 2, 3]
In [121]: li.pop()
Out[121]: 3
In [122]: li.pop()
Out[122]: 2
In [123]: li.pop()
Out[123]: 'fentiao'
In [124]: li
Out[124]: []
In [125]: li.pop()
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-125-bdc59cbfe7c0> in <module>()
----> 1 li.pop()
IndexError: pop from empty list
In [126]: del li ###删除列表###
In [127]: li
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-127-5ce4e85ef0aa> in <module>()
----> 1 li
NameError: name 'li' is not defined
In [128]:
练习:编写程序实现stack
#!/usr/bin/env python
#coding:utf-8
li = []
print "welcome to stack manage".center(50,'*')
Format = '''
please input:
p(U)sh
p(O)p
(V)iew
(Q)uit
'''
print Format
while True:
opera = raw_input("your choice:")
if opera == "U":
letter = raw_input("new item:")
li.append(letter)
print li
elif opera == "O":
if len(li)== 0:
print "stack is empty"
else:
li.pop()
print li
elif opera == "V":
if len(li) == 0:
print "stack is empty"
else:
print li
elif opera == "Q":
print "quit stack manage".center(50,"*")
exit(0)
else:
print "input u,o,v,q"
执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/untitled/3.py
*************welcome to stack manage**************
please input:
p(U)sh
p(O)p
(V)iew
(Q)uit
your choice:O
stack is empty
your choice:U
new item:ksjdfl
['ksjdfl']
your choice:V
['ksjdfl']
your choice:Q
****************quit stack manage*****************
Process finished with exit code 0
###练习###
打印1-100中所有的偶数
打印1-100中所有的奇数
In [143]: range(10)
Out[143]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [144]: range(1,10)
Out[144]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
In [145]: range(1,10,2)
Out[145]: [1, 3, 5, 7, 9]
In [146]: range(0,10,2)
Out[146]: [0, 2, 4, 6, 8]
####元组###
In [137]: t = (1,2,3,4) ###定义元组用()###
In [138]: t[0] ###索引###
Out[138]: 1
In [139]: t[2]
Out[139]: 3
In [140]: t[-1]
Out[140]: 4
In [141]: t[:] ###切片###
Out[141]: (1, 2, 3, 4)
In [142]: t[1:3]
Out[142]: (2, 3)
In [143]: t(0)=10 ###不可以对元组进行修改###
File "<ipython-input-143-a7946ca4067e>", line 1
t(0)=10
SyntaxError: can't assign to function call
In [144]: name,age,gender=('fentiao',5,'male') ###元组可以多个赋值###
In [145]: print name,age,gender
fentiao 5 male
In [146]: a,b,c = 1,2,3
In [147]: print a,b,c
1 2 3
In [148]: a,b,c = (1,2,3)
In [149]: print a,b,c
1 2 3
In [150]: a=(1)
In [151]: type(a)
Out[151]: int
In [152]: a=("hello")
In [153]: type(a)
Out[153]: str
In [154]: a=("hello",) ###如果要定义单个元组,需要加逗号###
In [155]: type(a)
Out[155]: tuple
In [156]: t = (1,2,(1,2),[1,2]) ###元组里的元素类型可以是多种的###
In [157]: type(t)
Out[157]: tuple
In [158]: t[3][1]=10 ###可以对元组的类型为列表的元素赋值###
In [159]: t
Out[159]: (1, 2, (1, 2), [1, 10])
In [161]: t = (1,2,3)*3
In [162]: t
Out[162]: (1, 2, 3, 1, 2, 3, 1, 2, 3)
In [163]: t1 = ('hello','world')
In [164]: t2 = ('westos','linux')
In [165]: print t1+t2
('hello', 'world', 'westos', 'linux')
######集合######
集合是一个无序的,不重复的数据组合
应用:
1 列表去重
2 关系测试:如交集,差集,并集的关系测试
集合一般不能定义为空,定义为空的话,会变成字典型
n [152]: set = {}
In [153]: type(set)
Out[153]: dict
In [154]:
小练习:输入一个英文句子,显示词的种类(去重)
a = raw_input("请输入一个英文句子:")
b = a.split()
lengthen = len(b)
print lengthen
c = set(b)
lengthen = len(c)
print lengthen
执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/untitled/4.py
input english:i like english very very much
5
Process finished with exit code 0
list1 = [1,2,3,4,1,2,3]
s1 = set(list1)
print s1
# print type(list1),type(s1)
s2 = {1,2,100,'hello'}
print s1.union(s2) ###s1与s2的并集###
print s1.intersection(s2) ###s1与s2的交集###
s1.intersection_update(s2) ###将s1与s2的交集更新给s1###
print s1
print s1.difference(s2) ###差集###
print s1.symmetric_difference(s2) ###对等差分###
本文转自blueclo51CTO博客,原文链接: http://blog.51cto.com/12774272/1945398,如需转载请自行联系原作者