Collation of python basic data types

1, Data type

(1) , tips

1. PyCharm: select multiple lines and press Ctrl + / "to comment them out in batch

(2) , string

1,startswith(str,[,start][,end])
#Determine whether the string starts with str
s = 'lichuanlei'
print(s.startswith('le',7,9))

Instance output result:

True
2,replace(str_old,str_new[,num])
#Replace string
s = 'lichuanlei'
print(s.replace('l','L',2))
print(s.replace('l','L'))

Instance output result:

LichuanLei
LichuanLei
3,strip
#Remove left and right strings
s = '   \n\tlichuanlei\n\t  '
print(s.strip())      #Remove leading and trailing spaces
s2 = 'lichuanlei'  
print(s2.strip('li'))  #Remove the first and last string 'li'

Instance output result:

lichuanlei
chuanle
4,split
#Separated by spaces by default, returns a list
#str-->list
s = 'Tom Mary Peter'
s2 = 'Tom:Mary:Peter'
s3 = ':Tom:Mary:Peter'
print(s.split())
print(s2.split(':'))
print(s3.split(':'))

Instance output result:

['Tom', 'Mary', 'Peter']
['Tom:Mary:Peter']
['', 'Tom', 'Mary', 'Peter']
5,join
t = 'Tom', 'Mary', 'Peter'
s = ['Tom', 'Mary', 'Peter']  #All elements in the list must be of str type
t2 = '+'.join(t)
s2 = ':'.join(s)
print(t2)
print(s2)

Instance output result:

Tom+Mary+Peter
Tom:Mary:Peter
6,count
s = 'abcdefgab'
s1 = s.count('a')
s2 = len(s)
print(s1)
print(s2)

Instance output result:

2
9
7,format
msg = 'My name is{},This year{}Age, gender{}!!!'.format('Tom','22','male')  #First usage
msg2 = 'My name is{0},This year{1}Age, gender{2},I still call it.{0}!!!'.format('Tom','22','male') #Second usage
msg3 = 'My name is{name},This year{age}Age, gender{sex}!!!'.format(name='Tom',sex='male',age=22) #Third usage
print(msg)
print((msg2))

Instance run result:

My name is Tom. I'm 22 years old, male!!!
My name is Tom. I'm 22 years old. My gender is male. My name is still Tom!!!
My name is Tom. I'm 22 years old, male!!!
8, is series
name = 'Tom123'
c = 'abcd'
num = '123'
print(name.isalnum())     #A string consists of letters or numbers
print(c.isalpha())        #A string consists of only letters
print(num.isdecimal())    #String is made up of decimal only
print(num.isnumeric())    #String is made up of decimal only

Instance output result:

True
True
True
True
9,upper lower
s = 'abcCDE'
print(s.upper())     #Capitalize all characters of string
print(s.lower())     #String all characters to lowercase

Instance output result:

ABCCDE
abccde

10. Format output print

s = '321'
for i in s:      #Placeholder, the following two print results are the same
    print('Count down{}second'.format(i))  #print('countdown% s seconds'% i)
print('Set out!')

Instance output result:

Countdown 3 seconds
 Countdown 2 seconds
 Countdown 1 second
 Set out!

(3) , cycle

1,while
s = 'lichuanlei'
count = 0
while count < len(s):
    print(s[count])
    count+=1

Instance output result:

l
i
c
h
u
a
n
l
e
i
2. for variable in iterable

eg1:

s = 'lichuanlei'   #Iteratable object
for n in s:
    print(n)

Instance output result:

l
i
c
h
u
a
n
l
e
i

eg2:

s = 'lichuanlei'
for i in s:
    print(i)
    if i == 'a':
        break

Instance output result:

l
i
c
h
u
a

eg3:

#Add multiple numbers
result = 0
num = input('Please input content (Format: 1+2+......): ')
lst1 = num.split('+')
for i in lst1:
    result = result+int(i)
print(result)

eg4:

#Determine how many numbers are in the string
content = input('Please input:')
result = 0
for i in content:
    if i.isdecimal():
        result +=1
print('Share%s Number'%result)

(four) list

1. Add elements

1.1 append: append

#Append: append
lst1 = ['Tom','Peter','Jerry']
while 1:
    name = input('Please enter the employee's name (press Q or q Exit):')
    if name.upper() == 'Q':
        break
    lst1.append(name)
print(lst1)

1.2 insert: Insert

# Insert add element
lst1 = ['Tom','Peter','Jerry']
lst1.insert(1,'Mary')
print(lst1)

Instance run result:

['Tom', 'Mary', 'Peter', 'Jerry']

1.3 extend: add iteratively

#Add iteratively
lst1 = ['Tom','Peter','Jerry']
lst1.extend('ABC')       #Three elements "A", "B" and "C" are added this time
lst1.extend(['ABC','Work','Job'])   #  This time, three elements' ABC ',' work 'and' job 'are added
print(lst1)

Instance run result:

['Tom', 'Peter', 'Jerry', 'A', 'B', 'C', 'ABC', 'Work', 'Job']
2. Delete element

2.1 pop: delete by index

lst1 = ['Tom','Peter','Jerry','Tom','Mary']
lst2 = ['Tom','Peter','Jerry']
pop1 = lst1.pop(-2)   #Delete by index (returned elements deleted)
pop2 = lst2.pop()   #Delete the last element by default (return the deleted element)
print(lst1,pop1)
print(lst2,pop2)

Instance run result:

['Tom', 'Peter', 'Jerry', 'Mary'] Tom
lst2 = ['Tom','Peter'] Jerry

2.2 remove: delete according to the specified element

lst1 = ['Tom','Peter','Jerry','Tom','Mary']
lst1.remove('Tom')     #Delete according to the specified element. If there are duplicate elements, the first element will be deleted from the left by default
print(lst1)

Instance run result:

['Peter', 'Jerry', 'Tom', 'Mary']

2.3 clear: clear

lst1 = ['Tom','Peter','Jerry','Tom','Mary']
lst1.clear()  #empty

2.4 del

lst1 = ['Tom','Peter','Jerry','Mary']
lst2 = ['Tom','Peter','Jerry','Tom','Mary']
del lst1[-2]      #Delete elements by index
del lst2[::2]     #Delete elements by slice step
print(lst1)
print(lst2)

Instance run result:

['Tom', 'Peter', 'Mary']
['Peter', 'Tom']
3. Change element
lst1 = ['Tom','Peter','Jerry','Mary']
lst2 = ['Tom','Peter','Jerry','Tom','Mary']
lst3 = ['Tom','Peter','Jerry','Tom']
lst1[1] = 'Sun WuKong'     #Change elements by index
lst2[2:] = 'ABCDEFGH'   #According to the slice change, the extra length increase will be added after
lst3[::2] = ['RR','YY']  #Change according to slice (step), quantity must correspond one by one
print(lst1)
print(lst2)
print(lst3)

Instance run result:

['Tom', 'Sun WuKong', 'Jerry', 'Mary']
['Tom', 'Peter', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
['RR', 'Peter', 'YY', 'Tom']
4, query
lst1 = ['Tom','Peter','Jerry','Mary']
lst2 = ['Tom','Peter','Jerry','Tom','Mary']
for i in lst1:         #Traverse all elements
    print(i)

print(lst2[-1])        #Query elements by index
print(lst2[::2])       #Query elements by slice (step)

Instance run result:

Tom
Peter
Jerry
Mary
Mary
['Tom', 'Jerry', 'Mary']
5. Nesting

eg1:

lst1 = [1,2,'taibai',[1,'alex',3]]
lst1[2] = lst1[2].upper()
lst1[3].append('Old boy Education')
lst1[-1][1] = lst1[-1][1]+'sb'
print(lst1)

Instance run result:

[1, 2, 'TAIBAI', [1, 'alexsb', 3, 'Old boy Education']]

eg2:

lst1 = [2,30,'k',['qwe',20,['k1',['tt',3,'1']],89],'ab','adv']
lst1[3][2][1][0] = lst1[3][2][1][0].upper()   #Change 'tt' in list lst1 to uppercase                
lst1[3][2][1][1] = '100'          #Change the number 3 in the list to the string '100'
lst1[3][2][1][2] = 101            #Change string '1' in the list to number 101
print(lst1)

Instance run result:

[2, 30, 'k', ['qwe', 20, ['k1', ['TT', '100', 101]], 89], 'ab', 'adv']

eg1:

#Judge whether a sentence is palindrome
content = input('Please input:')
if content == content[-1::-1]:
    print('%s It's palindrome!'%content)
else:
    print('%s It's not palindrome!'%content)

(five) tuple

c = 1,3
a,b = c
print(a,b)
a,b = b,a     #exchange
print(a,b)

Instance run result:

1 3
3 1

(six) range

for i in range(1,11): print(i,end='  ')  #Print 1 Ten
print('\n')
for i in range(1,11,2): print(i,end='  ')
print('\n')
for i in range(10,0,-1): print(i,end='  ')

Instance run result:

1  2  3  4  5  6  7  8  9  10  

1  3  5  7  9  

10  9  8  7  6  5  4  3  2  1 
lst1 = range(5)
print(lst1)
print(lst1[1:3])
print(lst1[-1])
for i in range(1,5,-1):
    print(i)     #Don't print anything

Instance run result:

range(0, 5)
range(1, 3)
4

(seven) dictionary

1. Create
#To create a dictionary:
dic = dict((('one',1),('two',2),('three',3)))    #First kind
dic2 = dict(one=1,two=2,three=3)        #Second kinds
dic3 = dict({'one':1,'two':2,'three':3})    #Third kinds
print(dic,'\n',dic2,'\n',dic3)

Instance run result:

{'one': 1, 'two': 2, 'three': 3}  
 {'one': 1, 'two': 2, 'three': 3} 
 {'one': 1, 'two': 2, 'three': 3}
2, increase

eg1:

dic = {'name':'Sun WuKong','age':26}
dic['sex'] = 'male'    #increase
dic['age'] = 28     #If there is something to change, there will be more
print(dic)

Instance run result:

{'name': 'Sun WuKong', 'age': 28, 'sex': 'male'}

eg2:

dic = {'name':'Sun WuKong','age':26}
dic['sex'] = 'male'    #increase
dic['age'] = 28     #If there is something to change, there will be more
dic.setdefault('hobby')     #Set default value for key: None null
dic.setdefault('hobby2','Run')
dic.setdefault('age',30)    #If there is one, it will remain unchanged; if there is none, it will increase
print(dic)

Instance run result:

{'name': 'Sun WuKong', 'age': 28, 'sex': 'male', 'hobby': None, 'hobby2': 'Run'}
3, delete
dic = {'name':'Sun WuKong','age':26,'sex':'male'}
dic2 = {'name':'Sun WuKong','age':26}
print(dic.pop('age'))     #Delete key value pairs according to the key, with return value
print(dic.pop('hobby','There is no such key.'))   #When the second parameter of pop is set, whether there is a key value right or not will not report an error
del dic['name']         #Press the key to delete the specified element, but there is no return value
dic2.clear()     #Clear key value pair content
print(dic)
print(dic2)

Instance run result:

26
 There is no such key.
{'sex': 'male'}
{}
4, change
dic = {'name':'Sun WuKong','age':26}
dic['age'] = 30
print(dic)

Instance run result:

{'name': 'Sun WuKong', 'age': 30}
5, check
dic = {'name':'Sun WuKong','age':26,'hobby_list':['Play a ball','run','climb']}
print(dic.get('hobby_list'))
print(dic.get('hobby_list2'))
print(dic.get('hobby_list2','There is no such key.'))  #Return value can be set
print(dic['name'])

Instance run result:

['play', 'run', 'climb']
None
 There is no such key.
Sun WuKong
6,keys()
dic = {'name':'Sun WuKong','age':26,'hobby_list':['Play a ball','Run','Mountain climbing']}
print(list(dic.keys()))     #Key to list
for key in dic:   #Another way to write: for key in dic.keys
    print(key)    #Key of traversal dictionary dic

Instance run result:

['name', 'age', 'hobby_list']
name
age
hobby_list
7,values()
dic = {'name':'Sun WuKong','age':26,'hobby_list':['Play a ball','Run','Mountain climbing']}
print(list(dic.values()))     #Values can be converted to lists
for value in dic.values():
    print(value)    #The value of traversal dictionary dic

Instance run result:

['Monkey King', 26, ['playing', 'running', 'climbing']]
Sun WuKong
26
 ['play', 'run', 'climb']
8,items()
dic = {'name':'Sun WuKong','age':26,'hobby_list':['Play a ball','Run','Mountain climbing']}
for value in dic.items():
    print(value)    #After traversing the items of dictionary dic, it becomes a tuple
for key,value in dic.items():    #Unpacking with tuples
    print(key,value)    #After traversing the items of dictionary dic

Instance run result:

('name', 'Sun WuKong')
('age', 26)
('hobby_list', ['Play a ball', 'Run', 'Mountain climbing'])
name Sun WuKong
age 26
hobby_list ['Play a ball', 'Run', 'Mountain climbing']

eg:

1. Add key value pair: 'k4':'v4 '; 2. Change' k1 'value to' alex '

3. Add a 44 to the K3 value; 4. Add a number 18 to the first position of K3 key

dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
dic.setdefault('k4','v4')     #Add key value pair: 'k4':'v4 '
dic['k1'] = 'alex'        #Change 'k1' value to 'alex'
dic['k3'].append(44)     #Add a 44 to k3
dic['k3'].insert(0,18)   #Add a number 18 to the first position of K3 key
print(dic)

Instance run result:

{'k1': 'alex', 'k2': 'v2', 'k3': [18, 11, 22, 33, 44], 'k4': 'v4'}
9. Nesting of dictionaries
#1. Get Wang Dian's name
#2. Get this dictionary: {'name': 'Zhang Yi', 'age':38}
#3. Get Wang Dian's wife's name
#4. Get the name of Wang Dian's third child
dic = {
    'name':'Wang Dian',
    'age':48,
    'wife':[{'name':'Zhang Yi','age':38},],
    'children':{'girl_first':'Little apple','girl_second':'Xiaoyi','girl_three':'Crest'}
}
print(dic.get('name'))
print(dic['wife'][0])
print(dic['wife'][0]['name'])
print(dic['children']['girl_three'])
10,update
dic = {'name':'Tom','age':28}
dic.update(hobby='motion',hight='175')     #Nothing increases.
dic.update(name='Marry')       #Yes, there are changes.
dic.update([(1,'one'),(2,'two'),(3,'three')])
print(dic)

(8) Exercises

eg1:
lst1 = []
lst2 = []
for i in list(range(100,9,-1)):   #100 ~ 10, add all even numbers to a new list in reverse order
    if i%2==0:
        lst1.append(i)
print('100-10 Even numbers:',lst1)
for i in lst1:
    if i%4 ==0:
        lst2.append(i)
print('100-10 Number divided by 4:',lst2)
eg2: remove the spaces for each element and find all elements that start with 'a' or 'a' and end with 'c'
#Look up the elements in list li, remove the spaces from each element, and find all elements that start with 'a' or 'a' and end with 'c',
#And add it to a new list, and print the list circularly
li = ['TaiBai  ','alexC','AbC','egon','  riTiAn','WuSir  ','  aqc',]
new_li = []
for i in li:
    new_i = i.strip()
    #if new_i.upper().startswith('A') and new_i.endswith('c'):  #The first method
    if new_i[0].upper() == 'A' and new_i[-1] == 'c':       #The second method
        new_li.append(new_i)
for i in new_li:
    print(i)   #Return value aqc
eg3: sensitive word filter
#Develop a sensitive word filter to prompt users to enter comments. If the comments contain special characters:
#List of sensitive words li = ['teacher Cang', 'Tokyo fever', 'taketo orchid', 'nodono's clothing']
#Then replace the sensitive words in the user's input with * of equal length (teacher Cang will replace with * * *), and add them to a list;
#If the content entered by the user has no sensitive vocabulary, it will be added directly to the above list.

li = ['Aoi Sora','Tokyo fever','Ran Asakawa','Yui Hatano']
comment_list = []
comment = input('Please enter your comment:')    #FDA gadfeaewer Cang, FDA evnk Cang, fdaie, wutenglan ewd32, bodono, and fdsfascf
for word in li:
    if word in comment:
        comment = comment.replace(word,'*'*len(word))
comment_list.append(comment)
print(comment_list)
eg4: loop print elements in nested list
#Cycle through each string in the list, including the strings in the nested list
li = ['TaiBai','alexC',['AbC','egon','riTiAn'],'WuSir','aqc',]
for i in li:
    if type(i) == list:
        for j in i:
            print(j)
    print(i)
eg5: space the elements in the list with ""
#Space elements in the list with ""
users = ['Zhang San','Li Si','Wang Wu',666,'Tom','Zhou Rong',888]
s = ''
for index in range(len(users)):
    if index == 0:
        s = s+users[index]
    else:
        s = s+'_'+str(users[index])
print(s)   #Return result: Zhang San, Li Si, Wang Wu, Tom, Zhou Rong
eg6: turn string into dictionary
#Change 'k1:1|k2:2|k3:3|k4:4|k5:5' to {k1:1, k2:2, k3:3, k4:4, k5:5}
msg = 'k1:1|k2:2|k3:3|k4:4|k5:5'
dic = {}
cc = msg.split('|')
for i in cc:
    key,value = i.split(':')
    dic[key] = int(value)
print(dic)

(nine) set

1. Description:

set. Container type data type. It requires that the elements in it are immutable data, but it itself is a variable data type. set is not required. {}

  • The function of set:
    1. List de duplication.
    2. Relation test: intersection, union, difference
2. Create:
set1 = {1,3,'Tom','Marry',False}
print(set1)
print({},type({}))    #Empty dictionary
set2 = set()         #Empty set
print(set2,type(set2))
3, increase
set1 = {1,3,'Tom','Marry',False}
set1.add('Jerry')     #Add an element
print(set1)
set1.update('ABCD')    #Add each element iteratively
print(set1)

Instance run result:

{False, 1, 'Jerry', 3, 'Tom', 'Marry'}
{False, 1, 'Jerry', 3, 'A', 'Tom', 'Marry', 'C', 'B', 'D'}
4, delete
set1 = {1,3,'Tom','Marry',False}
set1.remove('Tom')     #Delete by name
set1.pop()       #Random deletion
#set1.clear()   #Empty collection
#del set1      #Delete elements
print(set1)
5. Other operations:
5.1 intersection. (& or intersection)
set1 = {11,22,33,44,55}
set2 = {33,44,55,66,77,88}
print(set1 & set2)            #{33, 44, 55}
print(set1.intersection(set2))  #{33, 44, 55
5.2 Union. (| or union)
set1 = {11,22,33,44,55}
set2 = {33,44,55,66,77,88}
print(set1 | set2)   #{33, 66, 11, 44, 77, 22, 55, 88}
print(set1.union(set2))  #{33, 66, 11, 44, 77, 22, 55, 88}
5.3 difference set. (- or difference)
set1 = {11,22,33,44,55}
set2 = {33,44,55,66,77,88}
print(set1 - set2)   #{11, 22}
print(set1.difference(set2))  #{11, 22}
5.4 contrast set. (^ or symmetric_difference)
set1 = {11,22,33,44,55}
set2 = {33,44,55,66,77,88}
print(set1 ^ set2)   #{66, 22, 88, 11, 77}
print(set1.symmetric_difference(set2))  #{66, 22, 88, 11, 77}
5.5 subsets. (< or issubset)
set1 = {11,22,33,44,55}
set2 = {11,22,33,44,55,66,77,88,99}
print(set1 < set2)
print(set1.issubset(set2))  #Both of them are the same, which means set1 is a subset of set2.
5.6 superset. (> or issuperset)
set1 = {11,22,33,44,55}
set2 = {11,22,33,44,55,66,77,88,99}
print(set2 > set1)
print(set2.issuperset(set1))   ##The two are the same, which means set2 is a superset of set1.

eg1: List de duplication

L1 = [1,2,3,2,3,4,4,5,5,11,11,13,13,44,44]    #List removal
L1 = set(L1)
print(L1)

Keywords: Python Pycharm

Added by danger2oo6 on Tue, 18 Feb 2020 07:00:52 +0200