current position:Home>Python course notes -- Python string, detailed explanation of related functions
Python course notes -- Python string, detailed explanation of related functions
2022-05-15 05:50:00【Tang Keke, Laoxiang, Henan】
String encoding
- GBK2312 It is the Chinese code formulated by our country , use Two bytes for Chinese
- Unicode Put all languages into one set of codes , There will be no garbled code , Two bytes represent a character , Four characters are used for remote words
- UTF-8 It encodes the characters needed all over the world , yes “ Variable length encoding ”, Use a byte to represent the letter , Three bytes represent Chinese , Others are two or four bytes .
Python3.x Version default use UTF-8 Format encoding
Escape character
You put it in front of the string ’r’, perhaps ’R’, Indicates that the following string will not be escaped .
path = r'C:\windows\python.exe'
Formatting of strings
% format
Format
print('%d %s' % (a, b))
Symbolic meaning
‘-’ Specify left alignment
‘+’ Add before positive number + Number
‘.n’ Specify the precision
>>>'%.2f' % 0.33333
0.33
Format characters
and C++ Basically the same ,
- %d Decimal integer
- %e With e Bottom index
- %o Octal integer
format() Method to format
The basic grammar is through ’{}’,’:‘ Replace the previous ’%’
>>>'{:%}'.format(3.5)
'350.0000%'
The meaning of characters in various formats
Specify location parameters
"{}{}".format('Hello', 'World') # By default
>>> "{0}{1}{0}".format('Hello', 'World'') # The specified location
'World Hello World’
>>> print("my name is {
name}, my age is {
age}, and my QQ is
{
qq}".format(name = "Dong Fuguo",age = 40,qq = "30646****")) # Variable naming
my name is Dong Fuguo, my age is 40, and my QQ is 30646****
String preceded by f
And format The method is basically similar to
>>> name = 'Dong'
>>> age = 39
>>> f'My name is {
name}, and I am {
age} years old.'
'My name is Dong, and I am 39 years old.'
>>> width = 10
>>> precision = 4
>>> value = 11/3
>>> f'result:{
value:{
width}.{
precision}}'# Width and precision can be specified
'result: 3.667'
Common functions
find,rfind,count, index,rindex
find(str,beg=0,end=len(str))
rfind(str,beg=0,end=len(str)))
index(str,beg=0,end=len(str)))
rindex(str,beg=0,end=len(str)))
count()
- find() and rfind Methods are used to find a string within the specified range of another string ( The default is the entire string ) The position of the first and last appearance in , Returns if it does not exist -1
- index() and rindex() Method is used to return the position of the first and last occurrence of one string in the specified range of another string , If it doesn't exist Throw an exception
- count() Method is used to return the number of times a string appears in the current string
split()、rsplit()、partition()、rpartition()
split(str="", num=string.count(str))、rsplit(str="",num=string.count(str))
- split() and rsplit() Methods are used to separate with the specified character , Separate the current string from left to right or from right to left into multiple strings , And return a list of delimited results
- partition() and rpartition() Used to separate the original string with the specified string as the separator Divided into 3 part , namely String before separator 、 Separator string 、 String after separator , If the specified delimiter is not in the original string , Then return to The original string and two empty strings . Put the string string branch become One individual 3 element plain Of Tuples (string_pre_str,str,string_post_str)
join
Returns a new string generated by connecting elements in a sequence through a specified character .
>>> li = ["apple","peach","banana","pear"]
>>> ','.join(li)
'apple,peach,banana,pear'
lower()、upper()、capitalize()、title()、swapcase()
>>> s =
"What is Your Name?"
>>> s.lower() # Returns a lowercase string
'what is your name?'
>>> s.upper() # Returns the uppercase string
'WHAT IS YOUR NAME?'
>>> s.capitalize() # The first character of a string is capitalized 'What is your name?'
>>> s.title() # Capitalize each word 'What Is Your Name?'
>>> s.swapcase() # Case interchangeability
'wHAT IS yOUR nAME?'
replace()、maketrans()、translate()
replace
Search and replace replace(old, new[, max]), Be similar to Word Medium “ All replacement ” function
- old – Substring to be replaced
- new – New string , Used for replacement old Substring
- max – Optional string , Replace no more than max Time
Be careful : It returns a new string
>>> s =" China , China "
>>> print(s)
China , China
>>> s2 = s.replace(" China "," The People's Republic of China ")
>>> print(s2)
The People's Republic of China , The People's Republic of China
maketrans()、translate()
String object maketrans() Method is used to generate a character mapping table , and translate() Method is used to convert a string according to the correspondence defined in the mapping table and replace the characters in it , Using a combination of these two methods, you can process multiple characters at the same time .
# Create a mapping table , The character "abcdef123" Convert one-to-one into "[email protected]#$"
>>> table =
''.maketrans('abcdef123','[email protected]#$')
>>> s ="Python is a greate programming language. I like it!"
# Replace by mapping table
>>> s.translate(table)
'Python is u gryuty progrumming lunguugy. I liky it!'
Some commonly used whole letters , And realize Caesar encryption
lower = string.ascii_lowercase # Lowercase letters
upper = string.ascii_uppercase # Capital
before = string.ascii_letters
after = lower[k:] + lower[:k] + upper[k:] + upper[:k]
table =''.maketrans(before, after) # Create a mapping table
return s.translate(table)
strip()、rstrip()、lstrip()
>>> s =" abc "
>>> s.strip() # Delete white space characters
'abc'
>>> '\n\nhello world \n\n'.strip() # Delete white space characters
'hello world'
>>> "aaaassddf".strip("a") # Delete specified characters
'ssddf'
>>> "aaaassddf".strip("af")
'ssdd'
>>> "aaaassddfaaa".rstrip("a") # Delete the specified character at the right end of the string
'aaaassddf'
>>> "aaaassddfaaa".lstrip("a") # Delete the specified character at the left end of the string
'ssddfaaa'
Be careful , The strings specified by the parameters of these three functions are not treated as a whole , But on both sides of the original string 、 On the right side 、 Delete all characters contained in the parameter string on the left
>>> 'aabbccddeeeffg'.strip('gbaefcd')
''
startswith()、endswith()
s.startswith(t, beg=0,end=len(string))、s.endswith(t,beg=0,end=len(string)), Determines whether a string starts or ends with a specified string
>>> s = 'Beautiful is better than ugly.'
>>> s.startswith('Be') # Detect the entire string
True
>>> s.startswith('Be', 5) # Specify the starting position of the detection range
False
>>> s.startswith('Be', 0, 5) # Specify the start and end positions of the detection range
True
isalnum()、isalpha()、isdigit()、isspace()、isupper()、islower()
isalnum()、isalpha()、isdigit()、isspace()、isupper()、islower(), Used to test whether the string is a number or letter 、 Is it a letter 、 Whether it is a numeric character 、 Whether it is a blank character 、 Whether it is uppercase and lowercase .
>>> '1234abcd'.isalnum()
True
>>> '1234abcd'.isalpha() # Returns... When all letters are English True
False
>>> '1234abcd'.isdigit() # Returns... When all are numbers True
False
>>> 'abcd'.isalpha()
True
>>> '1234.0'.isdigit()
False
center()、ljust()、rjust()
center()、ljust()、rjust(), Returns a new string of the specified width , The original string is centered 、 Left or right alignment appears in the new string , If the specified width is greater than the string length , Then use the specified character ( Default is space ) Fill in .
>>> 'Hello world!'.center(20) # Align center , Fill with spaces
' Hello world! '
>>> 'Hello world!'.center(20,'=') # Align center , In characters = Fill in
'====Hello world!===='
>>> 'Hello world!'.ljust(20,'=') # Align left
'Hello world!========'
>>> 'Hello world!'.rjust(20,'=') # Right alignment
'========Hello world!'
String supported operators
+
Generate a new string
>>> 'hello ' + 'world'
'hello world'
in
Member judgment , keyword in
>>> "a" in "abcde" # Test whether one character exists in another string
True
>>> 'ab' in 'abcde'
True
>>> 'ac' in 'abcde' # keyword in The string on the left is treated as a whole
False
>>> "j" in "abcde"
False
*
Python Strings support multiplication with integers , Indicates sequence duplication , That is, the repetition of string content , Get the new string
>>> 'abcd' * 3
'abcdabcdabcd'
Built in functions for string objects
>>> x =
'Hello world.'
>>> len(x) # String length
12
>>> max(x) # The largest character
'w'
>>> min(x)
' '
>>> list(zip(x,x)) #zip() It can also act on strings
[('H','H'), ('e','e'), ('l','l'), ('l','l'), ('o','o'), (' ','',('w','w'), ('o','o'), ('r','r'), ('l','l'), ('d','d'), ('.','.')]
>>> sorted(x)
[' ','.','H','d','e','l','l','l','o','o','r','w']
>>> list(reversed(x))
['.','d','l','r','o','w',' ','o','l','l','e','H']
>>> list(enumerate(x))
[(0,'H'), (1,'e'), (2,'l'), (3,'l'), (4,'o'), (5,' '), (6,'w'),(7,'o'), (8,'r'), (9,'l'), (10,'d'), (11,'.')]
>>> list(map(add, x, x))
['HH','ee','ll','ll','oo',' ','ww','oo','rr','ll','dd','..']
copyright notice
author[Tang Keke, Laoxiang, Henan],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/131/202205110611060965.html
The sidebar is recommended
- Build Python project in Jenkins, pychar output is normal and Jenkins output modulenotfounderror: no module named problem
- Interface request processing of Python webservice
- Download third-party libraries offline in Python
- Web automation in Python
- Importlib.exe in Python import_ Module import module
- Operation of OS Library in Python
- Some integration operations on Web pages in Python
- Python realizes the super fast window screenshot, automatically obtains the current active window and displays the screenshot
- Implementation of workstation monitoring system with Python socket
- Resume Automation - word 92
guess what you like
Django foundation -- 02 small project based on Database
Python drawing word cloud
Django foundation -- 02 small project based on Database
MNIST dataset classification based on Python
Design of FTP client server based on Python
Signing using RSA algorithm based on Python
Website backend of online book purchase function based on Python
Implementation of Tetris game based on Python greedy search
Django Foundation
Case: Python weather broadcast system, this is a rainy day
Random recommended
- Python development alert notification SMS alert
- How to configure Python environment library offline in FME
- Python: fastapi - beginner interface development
- Generate password based on fast token and fast token
- [Django CI system] use of json-20220509
- [Django CI system] if the front-end date is complete, it will be fully updated to the back-end; If the front-end date is incomplete, the date will not be updated to the back-end-20220510
- [Django CI system] echarts dataset standard writing - 20220509
- [Django CI system] obtain the current time, the first day and the last day of the month, etc. - 20220510
- wxPython wx. Correction of font class · Wx Font tutorial
- NCT youth programming proficiency level test python programming level 3 - simulation volume 2 (with answers)
- Design of personal simple blog system based on Django (with source code acquisition method)
- [Python Script] classify pictures according to their definition
- Wu Enda's classic ml class is fully upgraded! Update to Python implementation and add more intuitive visual teaching
- Six built-in functions called immortals in Python
- Some insights of pandas in machine learning
- Introduction to Python [preliminary knowledge] - programming idea
- Stay up late to tidy up! Pandas text processing Encyclopedia
- Python recursion to find values by dichotomy
- Open 3D Python Interface
- [true title 02 of Blue Bridge Cup] Python output natural number youth group analysis of true title of Blue Bridge Cup Python national competition
- Introduction to the differences between Python and Java
- Explain Python CONDA in detail
- The pycham downloaded by MAC reports an error as soon as it is opened. The downloaded Python interpreter is also the latest version
- From entry to mastery, python full stack engineers have personally taught Python core technology and practical combat for ten years
- Python is used to detect some problems of word frequency in English text.
- How to choose between excel, database and pandas (Python third-party library)?
- WxPython download has been reporting errors
- Pyside6 UIC and other tools cannot be found in the higher version of pyside6 (QT for Python 6). How to solve it?
- About Python Crawlers
- Successfully imported pandas, unable to use dataframe
- How to extract some keywords in the path with Python
- Python encountered a problem reading the file!
- When Python is packaged into exe, an error is reported when opening assertionerror: C: \ users \ Acer \ appdata \ local \ temp\_ MEI105682\distutils\core. pyc
- Eight practical "no code" features of Python
- Python meets SQL, so a useful Python third-party library appears
- 100 Python algorithm super detailed explanation: a hundred dollars and a hundred chickens
- [fundamentals of Python] Python code and so on
- When Python uses probit regression, the program statement is deleted by mistake, and then it appears_ raise_ linalgerror_ Unrecognized error of singular
- Python testing Nicholas theorem
- Accelerating parallel computing based on python (BL) 136