首页 > 代码库 > python基础2

python基础2

python基础2

 



####字符串的基本操作###


字符串切片:

 

>>> 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‘

 

 

 

编写程序:判断输入的字符串是否符合变量的规则

 

import string

print "please input a string:"

a = raw_input()

if a[0] in string.letters + "_":

    for a in a[1:]:

        if a not in string.letters+string.letters+"_":

            print "faluse"

            exit(1)

 

    print "true"

else:print "faluse"

 

 

 

 

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

 

 

 

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 [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]: de

%%debug  %debug   def      del      delattr  

 

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

 

 

####元组###

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‘)

 

 

 

 

 

######集合###

 

 

a = raw_input("请输入一个英文句子:")

 

b = a.split()

lengthen = len(b)

print lengthen

c = set(b)

lengthen = len(c)

print lengthen

 

 

 

 

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)###对等差分###

 


python基础2