python-basic-string-list-tuple-dictionary

1 string

1.1 Subscripting and slicing

 1.2 Slicing

1.3 Common operations on strings

If there are strings mystr = 'hello world itcast and itcastcpp', the following are common operations

<1>find

Check whether str is included in mystr, if it is, return the starting index value, otherwise return -1

mystr.find(str, start=0, end=len(mystr))

 

<2>index

The same as the find() method, except that an exception will be reported if str is not in mystr.

mystr.index(str, start=0, end=len(mystr)) 

 

<3>count

Returns the number of times str appears in mystr between start and end

mystr.count(str, start=0, end=len(mystr))

 

<4>replace

Replace str1 in mystr with str2, if count is specified, the replacement will not exceed count times.

mystr.replace(str1, str2,  mystr.count(str1))

 

<5>split

Slice mystr with str as the delimiter, if maxsplit has a specified value, then only maxsplit substrings are separated

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

Check if the string starts with obj, return True if it is, otherwise return False

mystr.startswith(obj)

 

<9>endswith

Checks if the string ends with obj, returns True if so, False otherwise.

mystr.endswith(obj)

 

<10>lower

converts all uppercase characters in mystr to lowercase

mystr.lower()       

 

<11>upper

Convert lowercase letters in mystr to uppercase

mystr.upper()    

 

<12> bright

Returns a new string of length width that is left justified and padded with spaces

mystr.ljust(width) 

 

<13>rjust

Returns a new string of length width right-aligned from the original string and padded with spaces

mystr.rjust(width)  

 

<14>center

Returns a new string of length width centered on the original string and padded with spaces

mystr.center(width)   

 

<15>lstrip

remove whitespace characters to the left of mystr

mystr.lstrip()

 

<16>rstrip

remove whitespace at the end of mystr string

mystr.rstrip()    

 

<17>strip

Remove whitespace characters from both ends of mystr string

>>> a = "\n\t itcast \t\n"
>>> a.strip()
'itcast'

<18>rfind

Similar to the find() function, but searches from the right.

mystr.rfind(str, start=0,end=len(mystr) )

 

<19>rindex

Similar to index(), but starts from the right.

mystr.rindex( str, start=0,end=len(mystr))

 

<20>partition

Divide mystr into three parts by str, before str, after str and after str

mystr.partition(str)

 

<21>rpartition

Similar to the partition() function, but starts from the right.

mystr.rpartition(str)

 

<22>splitlines

Separated by lines, returns a list containing each line as an element

mystr.splitlines()  

 

<23>isalpha

Returns True if all characters in mystr are letters, otherwise returns False

mystr.isalpha()  

 

<24>isdigit

Returns True if mystr contains only numbers and False otherwise.

mystr.isdigit() 

 

<25>isalnum

Returns True if all characters of mystr are letters or numbers, otherwise returns False

mystr.isalnum()  

 

<26>isspace

Returns True if mystr contains only spaces, otherwise returns False.

mystr.isspace()   

 

<27>join

Insert str after each character in mystr to construct a new string

mystr.join(str)

 

 2 lists

2.1 Introduction to lists

 

2.2 List related operations

<1> Add elements ("increase" append, extend, insert )

append

Add elements to the list with 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) 

result:

extend

Extend can add elements from another collection to a 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 the element object before the specified position index

>>> a = [0, 1, 2]
>>> a.insert(1, 3) >>> a [0, 3, 1, 2] 

<2> Modify element ("change")

When modifying an element, it is necessary to determine which element to modify by subscripting, and then 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) 

result:

    -----修改之前,列表A的数据-----
    xiaoWang
    xiaoZhang
    xiaoHua
    -----修改之后,列表A的数据-----
    xiaoWang
    xiaoLu
    xiaoHua

<3> Find elements ("check" in, not in, index, count)

The so-called search is to see if the specified element exists

in, not in

Common methods of finding in python are:

  • in (exists), if it exists then the result is true, otherwise false
  • not in (not present), if not present 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)

 

illustrate:

As long as the in method can be used, then not in is also used in the same way, but not in judges that it does not exist

index, count

index and count are used the same as in strings

>>> a = ['a', 'b', 'c', 'a', 'b'] >>> a.index('a', 1, 3) # 注意是左闭右开区间 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: 'a' is not in list >>> a.index('a', 1, 4) 3 >>> a.count('b') 2 >>> a.count('d') 0 

<4> Delete elements ("delete" del, pop, remove)

Analogy in real life, if a classmate has changed classes, then the name of the student who has left should be deleted; this function is often used in development.

Common ways to delete list elements are:

  • del: delete according to the subscript
  • pop: remove the last element
  • remove: delete based on the value of the element

demo:(from)

    movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情'] print('------删除之前------') for tempName in movieName: print(tempName) del movieName[2] print('------删除之后------') for tempName in movieName: print(tempName) 

result:

    ------删除之前------
    加勒比海盗
    骇客帝国
    第一滴血
    指环王
    霍比特人
    速度与激情
    ------删除之后------
    加勒比海盗
    骇客帝国
    指环王
    霍比特人
    速度与激情

demo:(pop)

    movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情'] print('------删除之前------') for tempName in movieName: print(tempName) movieName.pop() print('------删除之后------') for tempName in movieName: print(tempName) 

result:

    ------删除之前------
    加勒比海盗
    骇客帝国
    第一滴血
    指环王
    霍比特人
    速度与激情
    ------删除之后------
    加勒比海盗
    骇客帝国
    第一滴血
    指环王
    霍比特人

demo:(remove)

    movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情'] print('------删除之前------') for tempName in movieName: print(tempName) movieName.remove('指环王') print('------删除之后------') for tempName in movieName: print(tempName) 

result:

    ------删除之前------
    加勒比海盗
    骇客帝国
    第一滴血
    指环王
    霍比特人
    速度与激情
    ------删除之后------
    加勒比海盗
    骇客帝国
    第一滴血
    霍比特人
    速度与激情

<5> Sort (sort, reverse)

The sort method is to rearrange the list in a specific order. The default is from small to large. The parameter reverse=True can be changed to reverse order, from large to small.

The reverse method reverses 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, lists also support nesting

An element in a list is another list, then this is the nesting of lists

    schoolNames = [['北京大学','清华大学'],
                    ['南开大学','天津大学','天津师范大学'], ['山东大学','中国海洋大学']] 

2. Application

A school has 3 offices, and now there are 8 teachers waiting for the assignment of workstations, please write a program to complete the random assignment

#encoding=utf-8

import random

#Define a list to hold 3 
offices = [[],[],[]]

#Define a list to store the names of 8 teachers 
names = [ ' A ' , ' B ' , ' C ' , ' D ' , ' E ' , ' F ' , ' G ' , ' H ' ]

i = 0
for name in names:
    index = random.randint(0,2)    
    offices[index].append(name)

i = 1
 for tempNames in offices:
     print ( ' The number of people in office %d is: %d ' % (i,len(tempNames)))
    i+=1
    for name in tempNames:
        print("%s"%name,end='')
    print("\n")
    print("-"*20)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325082832&siteId=291194637