1 string 1.1 Subscript and slice
1.2 Slices
1.3 Common String Operations
If there are strings mystr = ‘hello world itcast and itcastcpp‘
, the following are common operations
<1>find
Detects if STR is included in MyStr, or returns 1 if the index value is returned.
mystr.find(str, start=0, end=len(mystr))
<2>index
Just like the Find () method, only if STR does not report an exception in MyStr.
<3>count
Returns the number of times that STR appears in the mystr between start and end
mystr.count(str, start=0, end=len(mystr))
<4>replace
Replace the str1 in mystr with the STR2 if count specifies that the replacement is not more than count times.
mystr.replace(str1, str2, mystr.count(str1))
<5>split
Slice mystr with Str as delimiter, if Maxsplit has a specified value, only maxsplit substrings are delimited
mystr.split(str=" ", 2)
<6>capitalize
Capitalize the first character of a string
mystr.capitalize()
<7>title
Capitalize the first letter of each word in a string
>>> a = "hello itcast">>> a.title()‘Hello Itcast‘
<8>startswith
Checks whether the string starts with obj, or returns True, otherwise False
mystr.startswith(obj)
<9>endswith
Checks whether the string ends with obj, or returns False if True.
mystr.endswith(obj)
<10>lower
Convert all uppercase characters in mystr to lowercase
mystr.lower()
<11>upper
Convert lowercase letters in mystr to uppercase
mystr.upper()
<12>ljust
Returns the left alignment of an original string and fills the new string with the width of length with a space
<13>rjust
Returns the right alignment of the original string and fills the new string with the width of the length with a space
mystr.rjust(width)
<14>center
Returns the center of the original string and fills the new string with a space of length width
mystr.center(width)
<15>lstrip
Remove white space characters to the left of MyStr
mystr.lstrip()
<16>rstrip
Remove whitespace characters at the end of a mystr string
mystr.rstrip()
<17>strip
Remove whitespace characters at both ends of a mystr string
>>> a = "\n\t itcast \t\n">>> a.strip()‘itcast‘
<18>rfind
Similar to the Find () function, it is just looking from the right.
mystr.rfind(str, start=0,end=len(mystr) )
<19>rindex
Similar to index (), but starting from the right.
mystr.rindex( str, start=0,end=len(mystr))
<20>partition
The mystr is divided into three parts, str, str and STR
mystr.partition(str)
<21>rpartition
Similar to the partition () function, but starts from the right.
mystr.rpartition(str)
<22>splitlines
Returns a list containing rows as elements, separated by rows
mystr.splitlines()
<23>isalpha
Returns True if mystr all characters are letters, otherwise False
mystr.isalpha()
<24>isdigit
Returns True if the mystr contains only a number, otherwise False.
<25>isalnum
Returns True if all mystr characters are letters or numbers, otherwise False
mystr.isalnum()
<26>isspace
Returns True if the mystr contains only spaces, otherwise False is returned.
mystr.isspace()
<27>join
Insert Str after each character in the mystr to construct a new string
mystr.join(str)
2 Introduction to List 2.1 list
2.2 Related actions for a list
<1> Add elements ("append", Extend, insert)
Append
You can add elements to a list by append
Demo
#定义变量A,默认有3个元素 A = [‘xiaoWang‘,‘xiaoZhang‘,‘xiaoHua‘] print("-----添加之前,列表A的数据-----") for tempName in A: print(tempName) #提示、并添加元素 temp = input(‘请输入要添加的学生姓名:‘) A.append(temp) print("-----添加之后,列表A的数据-----") for tempName in A: print(tempName)
Results:
Extend
By extend you can add elements from another collection to the list one by one
>>> a = [1, 2]>>> b = [3, 4]>>> a.append(b)>>> a[1, 2, [3, 4]]>>> a.extend(b)>>> a[1, 2, [3, 4], 3, 4]
Insert
Insert (Index, object) inserts an element in the specified position before Index object
>>> a = [0, 1, 2]>>> a.insert(1, 3)>>> a[0, 3, 1, 2]
<2> modifying elements ("Change")
When modifying an element, use the subscript to determine which element is being modified before you can modify it.
Demo
#定义变量A,默认有3个元素 A = [‘xiaoWang‘,‘xiaoZhang‘,‘xiaoHua‘] print("-----修改之前,列表A的数据-----") for tempName in A: print(tempName) #修改元素 A[1] = ‘xiaoLu‘ print("-----修改之后,列表A的数据-----") for tempName in A: print(tempName)
Results:
-----修改之前,列表A的数据----- xiaoWang xiaoZhang xiaoHua -----修改之后,列表A的数据----- xiaoWang xiaoLu xiaoHua
<3> Find Element ("Check" in, not in, index, count)
The so-called lookup is to see if the specified element exists
In, not in
Common methods for finding in Python are:
- In (present), if present, the result is true, otherwise false
- Not in (does not exist) if it does not exist then the result is true, otherwise false
Demo
#待查找的列表 nameList = [‘xiaoWang‘,‘xiaoZhang‘,‘xiaoHua‘] #获取用户要查找的名字 findName = input(‘请输入要查找的姓名:‘) #查找是否存在 if findName in nameList: print(‘在字典中找到了相同的名字‘) else: print(‘没有找到‘)
Result 1: (found)
Result 2: (not found)
Description
If the in method is used, then the not in is the same usage, but not in the judgment is not there
Index, Count
Index and Count are the same as in the string
>>> a = [' A ',' B ',' C ',' A ',' B ']>>> A.index ( ' a ', 1, 3) # note is left closed right open interval traceback (most recent call last): File "<stdin > ", line 1, in <module>valueerror: ' a ' is not in list< Span class= "Hljs-prompt" >>>> a.index ( ' a ', 1, 4) 3>>> a.count ( b ') 2>>> a.count ( d ') 0
<4> Delete Element ("delete" Del, pop, remove)
In real life, if a classmate shifts, then the name of the student should be removed after the walk, and it is often used to remove this feature in development.
Common ways to delete list elements are:
- Del: Delete according to subscript
- Pop: Delete last element
- Remove: Delete based on the value of the element
Demo: (DEL)
movieName = [‘加勒比海盗‘,‘骇客帝国‘,‘第一滴血‘,‘指环王‘,‘霍比特人‘,‘速度与激情‘] print(‘------删除之前------‘) for tempName in movieName: print(tempName) del movieName[2] print(‘------删除之后------‘) for tempName in movieName: print(tempName)
Results:
------删除之前------ 加勒比海盗 骇客帝国 第一滴血 指环王 霍比特人 速度与激情 ------删除之后------ 加勒比海盗 骇客帝国 指环王 霍比特人 速度与激情
Demo: (POP)
movieName = [‘加勒比海盗‘,‘骇客帝国‘,‘第一滴血‘,‘指环王‘,‘霍比特人‘,‘速度与激情‘] print(‘------删除之前------‘) for tempName in movieName: print(tempName) movieName.pop() print(‘------删除之后------‘) for tempName in movieName: print(tempName)
Results:
------删除之前------ 加勒比海盗 骇客帝国 第一滴血 指环王 霍比特人 速度与激情 ------删除之后------ 加勒比海盗 骇客帝国 第一滴血 指环王 霍比特人
Demo: (remove)
movieName = [‘加勒比海盗‘,‘骇客帝国‘,‘第一滴血‘,‘指环王‘,‘霍比特人‘,‘速度与激情‘] print(‘------删除之前------‘) for tempName in movieName: print(tempName) movieName.remove(‘指环王‘) print(‘------删除之后------‘) for tempName in movieName: print(tempName)
Results:
------删除之前------ 加勒比海盗 骇客帝国 第一滴血 指环王 霍比特人 速度与激情 ------删除之后------ 加勒比海盗 骇客帝国 第一滴血 霍比特人 速度与激情
<5> sort (sort, reverse)
The sort method is to rearrange the list in a specific order, by default, from small to large, and the parameter reverse=true can be changed to reverse, from large to small.
The reverse method is to reverse the list.
>>> a = [1,4,2,3]>>> a[1, 4, 2, 3]>>> a.reverse ()>>> a[3, 2, 4, 1]>>> a.sort ()>>> a[1, 2, 3, 4]>>> a.sort (reverse= True) >>> a[4, 3, 2, 1]
2.3 List Nesting
1. List nesting
Similar to the nesting of while loops, the list also supports nested
A list of elements is a list, then this is the list of nested
schoolNames = [[‘北京大学‘,‘清华大学‘], [‘南开大学‘,‘天津大学‘,‘天津师范大学‘], [‘山东大学‘,‘中国海洋大学‘]]
2. Application
A school, there are 3 offices, now there are 8 teachers waiting for the allocation of positions, please write a program, complete the random allocation
#Encoding=utf-8ImportRandom#define a list of 3 offices to saveOffices = [[],[],[]]#define a list to store the names of 8 teachersnames = ['A','B','C','D','E','F','G','H']i=0 forNameinchNames:index= Random.randint (0,2) offices[index].append (name) I= 1 forTempnamesinchOffices:Print('Number of office%d:%d'%(I,len (tempnames))) I+=1 forNameinchTempnames:Print("%s"%name,end="') Print("\ n") Print("-"*20)
Next: http://www.cnblogs.com/liu-wang/p/8973643.html
python-Basics-strings-lists-ganso-dictionaries