Python notes
character string
I String introduction
1. Features
- A pair of quoted strings
name1='Jack' name2="Jerry"
- Three pairs of quoted string
name1='''Jack''' name2="""Jerry""" sen1='''I am Jack, nice to meet you!''' sen2="""I am Jack, nice to meet you too!"""
Note: string in three quotation marks supports line feed
# I'm Jack sen1="I'm Jack" sen2='I\'m Jack'
2. Output
name=Jack print('My name is%s' % name) print(f'My name is{name}')
3. Input
user=input('Please enter user name:') print(f'The user name you entered is:{user}') print(type(user))
Operation results:
Please enter user name: Jack The user name you entered is: Jack <class 'str'> Process finished with exit code 0
II subscript
Subscript is also called index, through which the corresponding data can be found quickly
Note: subscript starts from 0
Example:
name='Jack' print(name[0]) print(name[2]) print(name[3]) print(name[1])
Operation results:
J c k a Process finished with exit code 0
III section
Slicing refers to the operation of intercepting part of the operated object. String, list and tuple all support slicing operation.
1. Grammar
sequence[Start position subscript:End position subscript:step]
Note: the end position subscript is not included, and both positive and negative integers can be used; Step size is the selection interval, which can be positive or negative integers. The default step size is 1- 1 indicates the penultimate data.
2. Examples
name="abcdefghij" print(name[1:7:1]) # bcdefg print(name[1:7]) # bcdefg print(name[:7]) # abcdefg print(name[1:]) # bcdefghij print(name[::2]) # acegi print(name[:-1]) # abcdefghi print(name[-4:-1]) # ghi print(name[::-1]) # jihgfedcba
Operation results:
bcdefg bcdefg abcdefg bcdefghij acegi abcdefghi ghi jihgfedcba Process finished with exit code 0
IV Common operation methods
1. Find
Find the position or number of occurrences of the substring in the string
- find(): check whether the substring is included in the string. If it is, return the subscript of the starting position of the substring; otherwise, return - 1.
(1). grammar
String sequence.find(Substring,Start position subscript,End position subscript)
Note: the start position subscript and end position subscript can be omitted, indicating that they are searched in the whole string sequence.
(2). Examples
str="My name is Jack" print(str.find('is')) # 8 print(str.find('is',5,10)) # 8 print(str.find('names')) # -1
Operation results:
8 8 -1 Process finished with exit code 0
- index(): check whether the substring is included in the string. If it is, the subscript at the beginning of the substring will be returned. Otherwise, an exception will be reported.
(1). grammar
String sequence.index(Substring,Start position subscript,End position subscript)
Note: the start position subscript and end position subscript can be omitted, indicating that they are searched in the whole string sequence.
(2). Examples
str="My name is Jack" print(str.index('is')) # 8 print(str.index('is',5,10)) # 8 print(str.index('names')) # report errors
Operation results:
8 8 Traceback (most recent call last): File "C:/Users/Jack/Documents/test/temp.py", line 4, in <module> print(str.index('names')) # report errors ValueError: substring not found Process finished with exit code 1
- rfind(): the same function as find(), but the search direction starts from the right.
- rindex(): the same function as index(), but the search direction starts from the right.
- count(): returns the number of occurrences of the substring in the string.
(1). grammar
String sequence.count(Substring,Start position subscript,End position subscript)
Note: the start position subscript and end position subscript can be omitted, indicating that they are searched in the whole string sequence.
(2). Examples
str="My name is Jack and his name is Jerry" print(str.count('name')) # 2 print(str.count('is',5,10)) # 1 print(str.count('names')) # 0
Operation results:
2 1 0 Process finished with exit code 0
2. Modification
Modify the data in the string in the form of function
- replace(): replace
(1). grammar
String sequence.replace(Old substring,New substring,Replacement times)
Note: replacement times: if the occurrence times of the substring are found, the replacement times are the occurrence times of the substring.
(2). Examples
str="My name is Jack and his name is Jerry" print(str.replace('name','num')) # My num is Jack and his num is Jerry print(str.replace('name','num',1)) # My num is Jack and his name is Jerry print(str) # My name is Jack and his name is Jerry
Operation results:
My num is Jack and his num is Jerry My num is Jack and his name is Jerry My name is Jack and his name is Jerry Process finished with exit code 0
Note: data can be divided into variable type and immutable type according to whether it can be modified directly. When modifying string type data, the original string cannot be changed. It is an immutable type.
- split(): splits the string by the specified character.
(1). grammar
String sequence.split(Split character,num)
Note: num indicates the number of split characters. The number of data to be returned is num+1.
(2). Examples
str="My name is Jack and his name is Jerry" print(str.split('name')) # ['My ', ' is Jack and his ', ' is Jerry'] print(str.split('name',1)) # ['My ', ' is Jack and his name is Jerry'] print(str.split(' ')) # ['My', 'name', 'is', 'Jack', 'and', 'his', 'name', 'is', 'Jerry']
Operation results:
['My ', ' is Jack and his ', ' is Jerry'] ['My ', ' is Jack and his name is Jerry'] ['My', 'name', 'is', 'Jack', 'and', 'his', 'name', 'is', 'Jerry'] Process finished with exit code 0
Note: if the segmented character is a substring in the original string, the substring will be lost after segmentation.
- join(): combine strings with one character or substring, that is, combine multiple strings into a new string.
(1). grammar
Character or substring.join(A sequence of multiple strings)
(2). Examples
list1=['My','name','is','Jack'] list2=['I','am','Jack'] print('.....'.join(list1)) # My.....name.....is.....Jack print('+'.join(list2)) # I+am+Jack
Operation results:
My.....name.....is.....Jack I+am+Jack Process finished with exit code 0
- capitalize(): converts the first character of the string to uppercase, and all other characters are lowercase.
str="i am Jack" print(str.capitalize())
Operation results:
I am jack Process finished with exit code 0
- title(): converts the first letter of each word in the string to uppercase.
str="i am Jack" print(str.title())
Operation results:
I Am Jack Process finished with exit code 0
- lower(): converts uppercase to lowercase in the string.
str="I am Jack" print(str.lower())
Operation results:
i am jack Process finished with exit code 0
- upper(): convert the small case of the string to uppercase.
str="I am Jack" print(str.upper())
Operation results:
I AM JACK Process finished with exit code 0
- lstrip(): delete the blank character on the left of the string.
str=" I am Jack" print(str.lstrip()) # I am Jack
- rstrip(): delete the blank character at the right of the string.
str="I am Jack " print(str.rstrip()) # I am Jack
- strip(): delete the blank characters on both sides of the string.
str=" I am Jack " print(str.strip()) # I am Jack
- ljust(): returns a new string that is left aligned with the original string and filled with the specified character (default space) to the corresponding length.
(1). grammar
String sequence.ljust(length,Fill character)
(2). Examples
str='Jack' print(str.ljust(9,'e'))
Operation results:
Jackeeeee Process finished with exit code 0
- rjust(): returns a right aligned original string and fills it with the specified character (default space) to the corresponding length of the new string.
- center(): returns a new string centered on the original string and filled with the specified character (default space) to the corresponding length.
3. Judgment
To judge True or False, return True or False
- startwith(): check whether the string starts with the specified substring. If yes, it returns True; otherwise, it returns False. If the start and end position subscripts are set, search in the specified range.
(1). grammar
String sequence.startswith(Substring,Subscript start position,End position subscript)
(2). Examples
str="I am Jack" print(str.startswith('I')) # True print(str.startswith('I',4,7)) #False
- Endswitch(): check whether the string ends with the specified substring. If yes, it returns True; otherwise, it returns False. If the start and end position subscripts are set, search in the specified range.
(1). grammar
String sequence.endswith(Substring,Start position subscript,End position subscript)
(2). Examples
str="I am Jack" print(str.endswith('Jack')) # True print(str.endswith('Jack',4,7)) #False
- isalpha(): returns True if all characters in the string are letters; otherwise, returns False.
str1='username' str2='username001' print(str1.isalpha()) # True print(str2.isalpha()) # False
- isdigit(): returns True if all characters in the string are numbers; otherwise, returns False.
str1='001' str2='username001' print(str1.isdigit()) # True print(str2.isdigit()) # False
- isalnum(): returns True if the string is composed of numbers or letters; otherwise, returns False.
str1='username001' str2='username001-1' print(str1.isalnum()) # True print(str2.isalnum()) # False
Sunday Morning Call
06
Levi_5