加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python基础2之字符串、列表、字典、集合

发布时间:2020-12-16 23:55:22 所属栏目:Python 来源:网络整理
导读:table style="height: 30px; width: 1132px; background-color: #afeeee;" border="0" tr tdspan style="font-size: 16px; font-family: 'Microsoft YaHei';"一、python2 or python3 /td /tr /table 1.PRINT IS A FUNCTION Old: ,2*2 New: ( ,2*2 Old: x, Ol
<tr>
<td><span style="font-size: 16px; font-family: 'Microsoft YaHei';">一、python2 or python3</td>
</tr></table>

1.PRINT IS A FUNCTION

Old: ,2*2 New: (,2*2 Old: x, Old: New: () Old: >>sys.stderr, New: (,file= Old: (x,y) New: ((x,y))

2.某些库名改变

<table style="height: 30px; width: 1132px; background-color: #afeeee;" border="0">

3.ALL IS UNICODE NOW

<table style="height: 30px; width: 1132px; border: 0px solid #7fffd4; background-color: #afeeee;" border="0">

<tr>
<td><span style="font-size: 16px; font-family: 'Microsoft YaHei';">二、字符串拼接</td>
</tr></table>

name==+ wd

name= age=22 job= msg=% my name wd age 22 job IT

name= age=22 job= msg= .format(_name=name,_age=age,_job= my name age : 22 job : IT

name= age=22 job= msg= my name age : 22 job : IT

<table style="height: 30px; width: 1132px; background-color: #afeeee; ; width: 1132px;" border="0">

<tr>
<td><span style="font-family: 'Microsoft YaHei'; font-size: 16px;">三、字符串</td>
</tr></table>

1.字符串常用操作

string string center(self,width,fillchar= string count(self,sub,start=None,end= int decode(self,encoding=None,errors= object encode(self,errors= object endswith(self,suffix,end= bool expandtabs(self,tabsize= string find(self,end= int format(*args,**kwargs): string index(self,end= S.index(sub [,end]]) -> Like S.find() but ValueError when the substring 是否是字母和数字 S.isalnum() -> Return True all characters there at least one character 是否是字母 S.isalpha() -> Return True all characters there at least one character 是否是数字 S.isdigit() -> Return True all characters there at least one character 是否小写 S.islower() -> Return True all cased characters S are lowercase there at least one cased character S.isspace() -> Return True all characters there at least one character S.istitle() -> Return True S a titlecased string there character characters S.isupper() -> Return True all cased characters S are uppercase there at least one cased character 连接 S.join(iterable) -> Return a string which the concatenation of the strings iterable. The separator between elements 内容左对齐,右侧填充 S.ljust(width[,fillchar]) -> Return S left-justified a string of length width. Padding done using the specified fill character (default 变小写 S.lower() -> 移除左侧空白 S.lstrip([chars]) -> string If chars given None,remove characters If chars 分割,前,中,后三部分 S.partition(sep) -> Search the separator sep S, the separator itself, the part after it. If the separator found, S 替换 S.replace(old,new[,count]) -> old replaced by new. If the optional argument count S.rfind(sub [,end]]) -> Return the highest index S where substring sub such that sub arguments start end are interpreted as Return -1 S.rindex(sub [,end]]) -> Like S.rfind() but ValueError when the substring S.rjust(width[,fillchar]) -> Return S right-justified a string of length width. Padding done using the specified fill character (default S.rpartition(sep) -> Search the separator sep S,starting at the end of S, the part before it,the separator itself, separator found, two empty strings S.rsplit([sep [,maxsplit]]) -> Return a list of the words delimiter string,starting at the end of the string to the front. If maxsplit done. If sep specified S.rstrip([chars]) -> string If chars given None,remove characters If chars 分割, maxsplit最多分割几次 S.split([sep [,maxsplit]]) -> Return a list of the words delimiter string. If maxsplit splits are done. If sep specified whitespace string a separator 根据换行分割 S.splitlines(keepends=False) -> Return a list of the lines Line breaks are included given 是否起始 S.startswith(prefix[,end]]) -> Return True prefix can also be a tuple of strings to 移除两段空白 S.strip([chars]) -> string Return a copy of the string S with leading If chars given None,remove characters If chars 大写变小写,小写变大写 S.swapcase() -> converted to lowercase S.title() -> intab = outtab = trantab = str = str.translate(trantab, S.translate(table [,deletechars]) -> the optional argument deletechars are removed, translation table,which must be a string of length 256 If the table argument None,no translation applied the operation simply removes the characters S.upper() -> 方法返回指定长度的字符串,原字符串右对齐,前面填充0。 S.zfill(width) -> of the specified width. The string S x.(y) <==> x+y x.(y) <==> y x x.(y) <==> x==y S.(format_spec) -> x.() <==> x.name x.(y) <==> x[y] x.(i,j) <==> Use of negative indices x.(y) <==> x>=y x.(y) <==> x>y x.() <==> hash(x) str(object=) -> If the argument a string,the value x.() <==> len(x) x.(y) <==> x<=y x.(y) <==> x x.(y) <==> x%y x.(n) <==> x*n T.(S,...) -> a new object with type S,a subtype of T x.(y) <==> x!=y x.() <==> repr(x) x.(y) <==> y%x x.(n) <==> n*x S.() -> size of S memory, bytes x.() <==> str(x)

<table style="height: 30px; width: 1132px; background-color: #afeeee; ; width: 1132px;" border="0">

<tr>
<td><span style="font-family: 'Microsoft YaHei'; font-size: 16px;">四、列表、元祖</td>
</tr></table>

1.列表(list)

列表常用操作:

a=[,,,1,2,3 (a.index()) a=[,,3 (a.index( (a.index(,5)) 3

>>> names = [,,,,, >>> names[1:4] [,, >>> names[1:-1] [,, >>> names[0:3 [,, >>> names[:3] [, >>> names[3:] [,, >>> names[3:-1] [, >>> names[-3:-1] [, >>> names[0::2] [, >>> names[::2] [,]

追加(append)

a=[,3 a.append( [,,,,3,]

a=[, [, a=[, (a) [, a=[, a.pop(2) [,]

a=[,3 a.insert(0,) [,3]

扩展(extend)

a=[, b=[1,3 [,3]

统计(count)

>>> [,,,, >>> >>> [,,, >>> names.reverse() >>> [,]

排序(sort)

>>> [,3 >>> names.sort() File ,line 1, TypeError: unorderable types: int() < str() >>> names[-3] = >>> names[-2] = >>> names[-1] = >>> [, >>> >>> [, >>> names.reverse() >>> [,]

循环(for)

a=[, i d

a=[,, ( oh you are here!

长度(len)

a=[, 3

清空(clear)

a=[, []

列表中含有的方法:

new empty list new list initialized from iterable's items append(self,p_object): count(self,value): integer -- return number of occurrences of value extend(self,iterable): index(self,value,stop=None): integer -- return first index of value. insert(self,index,p_object): pop(self,index=None): item -- remove and return item at index (default last). remove(self,value): reverse(self): sort(self,cmp=None,key=None,reverse=False): -1,1 (self,y): x+y (self,y): y in x (self,y): del x[y] (self,j): del x[i:j] (self,y): x==y (self,name): x.name (self,y): x[y] (self,j): x[i:j] (self,y): x>=y (self,y): x>y (self,y): x+=y (self,y): x*=y (self,seq=()): new empty list new list initialized from iterable's items (self): iter(x) (self): len(x) (self,y): x<=y (self,y): x (self,n): x*n @staticmethod (S,*more): (self,y): x!=y (self): repr(x) (self): (self,n): n*x (self,y): x[i]=y (self,j,y): x[i:j]=y (self): = list

2.元祖(tuple)

  • 索引
  • 切片
  • 循环
  • 长度
  • 包含

<table style="height: 30px; width: 1132px; background-color: #afeeee; ; width: 1132px;" border="0">

<tr>
<td><span style="font-family: 'Microsoft YaHei'; font-size: 16px;">五、字典</td>

</tr>

</table>

3.字典

字典的特性:

  • dict是无序的
  • key必须是唯一的,天生去重

字典操作:

索引(key)

a={:,:,: (a[ WD

增加?

a={:,: a[]= {: ,: ,: ,: }

修改

a={:,: a[]= {: ,: }

删除(del、pop)

>>> {: ,: ,: >>> info.pop() >>> {: ,: >>> info[] >>> {: >>> >>> >>> >>> info = {: ,: >>> {: ,: } >>> (, >>> {: }

查找(get)?

>>> msg={:,:22,: >>> msg[] >>> msg >>> msg.get()
键、值、键值对
msg={:,: (msg.keys()) (msg.values()) (msg.items()) dict_keys([,, dict_values([,22, dict_items([(,),(,22),(,)])

循环(for、enumerate)

key k,v info.items(): enumerate a={:,: i,k enumerate(a.keys()): 0 22 1 2 WD

长度(len)

msg={:,: 3
其他操作(update、setdefault)
update a={:,: b={:,:33,: {: ,: 33,: ,: setdefault a={:,: a.setdefault(, {: ,: 22}

字典中含有的方法:

new empty dictionary new dictionary initialized from a mapping object's new dictionary initialized as if via: new dictionary initialized with the name=value pairs clear(self): None. Remove all items from D. copy(self): a shallow copy of D @staticmethod fromkeys(S,v=None): New dict with keys from S and values equal to v. get(self,k,d=None): D[k] if k in D,else d. d defaults to None. has_key(self,k): True if D has a key k,else False items(self): list of D's (key,value) pairs,as 2-tuples iteritems(self): an iterator over the (key,value) items of D iterkeys(self): an iterator over the keys of D itervalues(self): an iterator over the values of D keys(self): list of D's keys pop(self,d=None): v,remove specified key and return the corresponding value. popitem(self): (k,v),remove and return some (key,value) pair as a setdefault(self,d=None): D.get(k,d),also set D[k]=d if k not in D update(self,E=None,**F): None. Update D from dict/iterable E and F. values(self): list of D's values viewitems(self): a set-like object providing a view on D's items viewkeys(self): a set-like object providing a view on D's keys viewvalues(self): an object providing a view on D's values (self,y): cmp(x,y) (self,k): True if D has a key k,else False (self,y): del x[y] (self,y): x==y (self,name): x.name (self,y): x[y] (self,y): x>=y (self,y): x>y (self,seq=None,**kwargs): new empty dictionary new dictionary initialized from a mapping object's new dictionary initialized as if via: new dictionary initialized with the name=value pairs (self): iter(x) (self): len(x) (self,y): x<=y (self,y): x @staticmethod (S,*more): (self,y): x!=y (self): repr(x) (self,y): x[i]=y (self): size of D in memory,in bytes = dict

<table style="height: 30px; width: 1132px; background-color: #afeeee; ; width: 1132px;" border="0">

<tr>
<td><span style="font-family: 'Microsoft YaHei'; font-size: 16px;">六、集合</td>
</tr></table>

集合是一个无序的,不重复的数据组合,特性:

  • 去重,把一个列表变成集合,就自动去重了
  • 关系测试,测试两组数据之前的交集、差集、并集等关系
常用操作:
s = set([3,5,9,10]) t = set() a = t | s b = t & s c = t – s d = t ^ s t.add() s.update([10,37,42]) t.remove( x x s <= s >= s | s & s - s ^ 返回 set “s”的一个浅复制

<table style="height: 30px; width: 1132px; background-color: #afeeee; ; width: 1132px;" border="0">

<tr>
<td><span style="font-family: 'Microsoft YaHei'; font-size: 16px;">七、练习题</td>
</tr></table>

1.三级菜单

需求:

1. 运行程序输出第一级菜单2. 选择一级菜单某项,输出二级菜单,同理输出三级菜单3. 菜单数据保存在文件中

代码:

flag= menu_list=[] menu_key=[] menu = {} with open (,,encoding= line msg=line.strip().split() msg[0] menu_key.append(msg[0]) menu_list.append(msg) city menu_key: menu3 = {} each menu_list: city== key,value=each[1].split( )[0],each[1].split( )[1:] menu3[key]=value menu[city]=menu3 i choice=input( choice i1 choice1 = input( choice1 i2 choice2 = input( choice2 == flag = choice2 == ( choice1== flag= choice1== choice== flag=
成都市:高新区 X公司 Y公司 Z公司
menu = exit_flag = current_layer = layers = k choice = input(>: choice == current_layer = layers[-1 choice current_layer: current_layer = current_layer[choice]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读