First , We know Python 3 in , Yes 6 Standard data types , They are divided into variable and immutable .
Immutable data (3 individual ):
Variable data (3 individual ):
This is a Python 3 Medium 6 Standard data types , It includes their basic usage and common methods , It will be listed below , For future reference . First , We need to know about operators , Because these data types often use these operations and so on .
See :Python Operator
# String form : Use '' perhaps "" Create string
str1 ='this is str1'
print(str1)
# 1.upper() Converts all lowercase letters in a string to uppercase
# character string .upper()
s1 = "hello Python"
print(s1.upper()) # HELLO PYTHON
#2.lower() Converts all uppercase letters in a string to lowercase
# character string .lower()
s2 = "HELLO PYTHON"
print(s2.lower()) # hello python
#3.swapcase() Swap the upper and lower case letters in the string
# character string .swapcase()
s3 = "hello PYTHON"
print(s3.swapcase()) # HELLO python
#4.title() Title The letters in the string ( Capitalize the first letter of each word )
# character string .title()
s4 = "hello python hello world"
print(s4.title()) # Hello Python Hello World
#5.capitalize() Make the first letter in the string uppercase Capital function
# character string .captialize()
s5 = "hello python hello world"
print(s5.capitalize()) # Hello python hello world
# 1.isupper() Check whether the string is composed of uppercase letters
# Variable .isupper()
# 2.islower() Check whether the string is composed of lowercase letters
# Variable .islower()
# 3.istitle() Check whether the string meets the title requirements
# Variable .istitle()
# 4.isalnum() Check whether the string is composed of numbers, letters and text
# Variable .isalnum()
# 5.isalpha() Check whether the string is composed of letters and text
# Variable .isalpha()
# 6.isdigit() Detect whether the string is 10 Hexadecimal characters ( Numbers ) *
# True: Unicode Numbers ,byte Numbers ( Single byte ), Full angle numbers ( Double byte )
# False: Chinese characters and numbers
# Error: nothing
# Variable .isdigit()
# 7.isnumeric() Check whether the string is composed of numeric characters ( Numbers )
# True: Unicode Numbers , Full angle numbers ( Double byte ), Chinese characters and numbers
# False: nothing
# Error: byte Numbers ( Single byte )
# Variable .isnumeric()
# 8.isspace() Detect whether the string is composed of white space characters ( Invisible characters ) form *
# Variable .isspace()
# 1.startswith() Checks whether the string starts with the specified string *
# Variable .startswith(' Detected string ')
# 2.endswith() Checks whether the string ends with the specified string *
# Variable .endswith(' Detected string ')
# 1.center() Fills the string to the specified length with the specified characters , Center the original content
# Variable .center( Fill length )
# Variable .center( Fill length , Fill character )
# 2.ljust() Fills the string to the specified length with the specified characters , Align the original content to the left
# Variable .ljust( Fill length )
# Variable .ljust( Fill length , Fill character )
# 3.rjust() Fills the string to the specified length with the specified characters , Align the original content to the right
# Variable .rjust( Fill length )
# Variable .rjust( Fill length , Fill character )
# 4.zfill() zero fill Zero fill effect ( That is, the length is not enough 0 fill ), Keep the content to the right
# Variable .zfill( The length of the entire string )
# 1.split() Cut a string with a specific string *
# Variable .split( Cut characters )
# Variable .split( Cut characters , Number of cuts )
# 2.join() Concatenate container data into a string using a specific string *
# Specific string .join( Containers )
# 1.strip() Remove the consecutive characters specified on the left and right sides of the string *
# Variable .strip() By default, the left and right space characters are removed
# Variable .strip( Removed specified string )
# 2.lstrip() Removes the consecutive characters specified to the left of the string
# Variable .lstrip() By default, the left and right space characters are removed
# Variable .lstrip( Removed specified string )
# 3.rstrip() Removes the consecutive characters specified to the right of the string
# Variable .rstrip() By default, the left and right space characters are removed
# Variable .rstrip( Removed specified string )
Tuples are similar to lists , Tuple use () Express . The inner elements are separated by commas , Tuples are immutable , You cannot assign values twice , Equivalent to read-only list .
t = (100,'xiaoming','hello',1.23)
print(t[0]) # 100
t[3] = 666 # This is an illegal application
# TypeError: 'tuple' object does not support item assignment
list = [10,'a']
list.append('b')
print(list)
# result : [10, 'a', 'b']
list = [10,'a']
list.insert(1,'b')
print(list)
# result : [10, 'b', 'a']
Be careful : append() and insert() The method is the list method , Can only be called on a list , Cannot call... On other values , For example, strings and integers .
list = [10,'a']
list = list + ['b']
print(list)
# result : [10, 'a', 'b']
list = [10,'a']
list.extend([20,'b'])
print(list)
# result : [10, 'a', 20, 'b']
Be careful : Additional append() and Expand extend() Differences in methods :append() The method is to add the element decomposition of the data type to the list ;extend() Method to add the element as a whole .
list = [10,'a']
list2 = list * 3
print(list2)
# result : [10, 'a', 10, 'a', 10, 'a']
list = [10,'a','b']
del list[1]
print(list) # result : [10, 'b']
del list
print(list) # result : <class 'list'>
list = [10,'a','b',30,'a']
list.remove('a')
print(list) # result : [10, 'b', 30, 'a']
list.remove('c')
print(list)
# Throw an exception
# Traceback (most recent call last):
# [10, 'b', 30, 'a']
# File "C:Desktop/Test.py", line 10, in <module>
# list.remove('c')
# ValueError: list.remove(x): x not in list
If you know the subscript of the value to be deleted in the list ,del Statements are easy to use . If you know the value you want to delete from the list ,remove() It's easy to use .
list = [10,'a','b',30]
print(list.pop(1)) # result : a
print(list) # result : [10, 'b', 30]
print(list.pop(6)) # result : IndexError: pop index out of range
# positive sequence
num = [2,5,-1,3.14,8,22,10]
num.sort()
print(num)
# Output : [-1, 2, 3.14, 5, 8, 10, 22]
print(sorted(num))
# Output : [-1, 2, 3.14, 5, 8, 10, 22]
# sort() and sorted() Method , The usage of the two is different
# The reverse
# Appoint reverse The key parameter is True
num = [2,5,-1,3.14,8,22,10]
num.sort(reverse=True)
print(num)
# Output : [22, 10, 8, 5, 3.14, 2, -1]
print(sorted(num,reverse=True))
# Output : [22, 10, 8, 5, 3.14, 2, -1]
About sort() The method should pay attention to :num = [2,5,-1,3.14,8,22,10]
num = num.sort() # Wrong operation
print(num)
str1 = [1,3,5,7,'hello','world']
str1.sort()
print(str1)
# TypeError: '<' not supported between instances of 'str' and 'int'
str1 = ['A','a','B','b','C','c']
str1.sort()
print(str1)
# Output : ['A', 'B', 'C', 'a', 'b', 'c']
# Sort in normal dictionary order
str2 = ['A', 'a', 'B', 'b', 'C', 'c']
str2.sort(key=str.lower) # Treat all items in the list as lowercase
print(str2)
info = {
'name':'zz','age':18}
info['age'] = 20 # Key already exists , Cover
info['job'] = 'student' # The key doesn't exist , newly added
print(info) # result : {'name': 'zz', 'age': 20, 'job': 'student'}
info = {
'name':'zz','age':18}
info1 = {
'name':'hh','sex':' male ','money':8000}
info.update(info1)
print(info)
# result : {'name': 'hh', 'age': 18, 'sex': ' male ', 'money': 8000}
info = {
'name':'zz','age':18,'sex':' male '}
info.clear()
print(info) # result : {}
info = {
'name':'zz','age':18,'sex':' male '}
del info['name'] # Delete key is 'name' The key/value pair
print(info) # result : {'age': 18, 'sex': ' male '}
del info # Empty dictionary
print(info)
# Throw an exception :
# Traceback (most recent call last):
# {'age': 18, 'sex': ' male '}
# File "C:/Desktop/Test.py", line 26, in <module>
# print(info)
# NameError: name 'info' is not defined
Here you can think about , Why clear() There is no exception when deleting the dictionary ?info = {
'name':'zz','age':18,'sex':' male '}
print(info.pop('name')) # result : zz
print(info) # result : {'age': 18, 'sex': ' male '}
info = {
'name':'zz','age':18,'sex':' male '}
pop_info = info.popitem() # Randomly return and delete a key value pair
print(pop_info)
# The output may be : ('sex', ' male ')
Be careful : aggregate (set) It's a Disordered non repetition Sequence of elements .
# 1. Create set
info = set('hello')
print(info)
# Possible result : {'l', 'e', 'o', 'h'}
Python There are two common ways to add collections , Namely add() and update().
info = {
'h', 'e', 'l', 'o'}
info.add('python')
print(info)
# Possible result : {'h', 'e', 'python', 'l', 'o'}
info = {
'h', 'e', 'l', 'o'}
info.update('python')
print(info)
# Possible result : {'n', 'e', 't', 'o', 'h', 'y', 'p', 'l'}
info = {
'h', 'e', 'python', 'l', 'o'}
info.remove('python')
print(info)
# Possible result : {'e', 'l', 'h', 'o'}
Articles you may be interested in :