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

python基础2之字符串、列表、字典、集合,第1张

概述内容概要:一、python2 or 3二、字符串拼接三、字符串四、列表、元祖五、字典六、集合七、练习 一、python2 or python3目前大多使用python2.7,随着时间的推移,python3将会成为python爱好者的主流。python2和3区别:1.PRINT IS A FUNCTION1 Old: print "The answer is", 2*2 New: print("The answer is", 2*2)2 Old: print x, # Trailing comma suppresses newline New: print(x, end=" ") # Appends a space instead of a newline3 Old: print # Prints a newline4 New: print() # You must call the function!5 Old: print >>sys.stderr, "fatal error" New: print("fatal error", file=sys.stderr)6 Old: print (x, y) # prints repr((x, y))7 New: print((x, y)) # Not the same as print(x, y)!2.某些库名改变例如:2.x3.x_winregwinregcopy_regcopyregQueuequeueSockerServersockerserverreprreprlib3.ALL IS UNICODE NOW所有的字符编码变为unicode 二、字符串拼接方法一:使用“+”(不推荐)原因:python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,万恶的+号每出现一次就会在内从中重新开辟一块空间name="wd"msg="my name is "+nameprint(msg)输出:my name is wd方法二:使用格式化字符串%s:字符串%d:整数%f:浮点数1 name="wd"2 age=223 job="IT"4 msg="my name is %s age %d job %s"%(name,age,job)5 print(msg)6 输出:7 my name is wd age 22 job IT方法三:使用format进行格式化输出(变量名替换)1 name="wd"2 age=223 job="IT"4 msg='''my name is:{_name}5 age is: {_age}6 job is: {_job}'''.format(_name=name,_age=age,_job=job)7 print(msg)8 输出:9 my name is:wd10 age is: 2211 job is: IT或者:(位置替换)1 name="wd"2 age=223 job="IT"4 msg='''my name is:{0}5 age is: {1}6 job is: {2}'''.format(name,age,job)7 print(msg)8 输出:9 my name is:wd10 age is: 2211 job is: IT总结:对比以上三种方法,使用+方式进行拼接字符串会开辟较多的内存空间,效率低,推荐使用第二种和第三种方法。 三、字符串1.字符串常用 *** 作移除空白(strip)分割(split)长度(len)索引(index)切片字符串对方法如下:1 class str(basestring):2 """3 str(object='') -> string45 Return a nice string representation of the object.6 If the argument is a string, the return value is the same object.7 """8 def capitalize(self):9 """ 首字母变大写 """10 """11 S.capitalize() -> string1213 Return a copy of the string S with only its first character14 capitalized.15 """16 return ""1718 def center(self, width, fillchar=None):19 """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """20 """21 S.center(width[, fillchar]) -> string2223 Return S centered in a string of length width. Padding is24 done using the specified fill character (default is a space)25 """26 return ""2728 def count(self, sub, start=None, end=None):29 """ 子序列个数 """30 """31 S.count(sub[, start[, end]]) -> int3233 Return the number of non-overlapping occurrences of substring sub in34 string S[start:end]. Optional arguments start and end are interpreted35 as in slice notation.36 """37 return 03839 def decode(self, encoding=None, errors=None):40 """ 解码 """41 """42 S.decode([encoding[,errors]]) -> object4344 Decodes S using the codec registered for encoding. encoding defaults45 to the default encoding. errors may be given to set a different error46 handling scheme. Default is 'strict' meaning that encoding errors raise47 a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'48 as well as any other name registered with codecs.register_error that is49 able to handle UnicodeDecodeErrors.50 """51 return object()5253 def encode(self, encoding=None, errors=None):54 """ 编码,针对unicode """55 """56 S.encode([encoding[,errors]]) -> object5758 Encodes S using the codec registered for encoding. encoding defaults59 to the default encoding. errors may be given to set a different error60 handling scheme. Default is 'strict' meaning that encoding errors raise61 a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and62 'xmlcharrefreplace' as well as any other name registered with63 codecs.register_error that is able to handle UnicodeEncodeErrors.64 """65 return object()6667 def endswith(self, suffix, start=None, end=None):68 """ 是否以 xxx 结束 """69 """70 S.endswith(suffix[, start[, end]]) -> bool7172 Return True if S ends with the specified suffix, False otherwise.73 With optional start, test S beginning at that position.74 With optional end, stop comparing S at that position.75 suffix can also be a tuple of strings to try.76 """77 return False7879 def expandtabs(self, tabsize=None):80 "

<table border="0"><tr>
<td><span >一、python2 or python3</td>
</tr></table>

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

<table border="0">

<tr>
<td><span >二、字符串拼接</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 border="0">

<tr>
<td><span >三、字符串</td>
</tr></table>

string string center(self,wIDth,fillchar= string count(self,sub,start=None,end= int decode(self,enCoding=None,errors= object encode(self,errors= @H_878_404@ 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 border="0">

<tr>
<td><span >四、列表、元祖</td>
</tr></table>

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!

a=[, 3

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): @H_735_2301@ -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 border="0">

<tr>
<td><span >五、字典</td>

</tr>

</table>

字典的特性:

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 border="0">

<tr>
<td><span >六、集合</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 border="0">

<tr>
<td><span >七、练习题</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(@H_860_4502@>: choice == current_layer = layers[-1 choice current_layer: current_layer = current_layer[choice] 总结

以上是内存溢出为你收集整理的python基础2之字符串、列表、字典、集合全部内容,希望文章能够帮你解决python基础2之字符串、列表、字典、集合所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1207912.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)