current position:Home>Python notes (V): string operation
Python notes (V): string operation
2022-01-30 10:43:54 【A bowl week】
Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .
Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~
Definition of string
So-called character string , Is the 0 One or more A finite sequence of characters .
stay Python In the program , If we put single or multiple characters in single quotation marks ''
Or double quotes ""
Wrap it up , Can represent a string , You can also break lines with three single quotes or double quotes . The characters of a string can be special symbols 、 English letter 、 Chinese characters 、 Hiragana or Katakana in Japanese 、 The Greek letter 、Emoji Characters and so on .
The following code shows Python String in :
text1 = " This is a string wrapped in double quotes "
text2 = ' This is a string wrapped in single quotes '
text3 = """ This is string wrapped in three quotation marks You can keep the original format """
print(text1)
print(text2)
print(text3)
Copy code
The code runs as follows :
This is a string wrapped in double quotes
This is a string wrapped in single quotes
This is string wrapped in three quotation marks
You can keep the original format
Copy code
Escape string and original string
Python Use a backslash in “” To express escape , in other words
The following content will not be the original content , for example \n
It means to wrap , Instead of saying And character
n 了 ; So if the string itself contains
'、
"、
These special characters , Must pass `` Escapes .
The sample code is as follows :
text1 = "\'Hello world\'" # The output is wrapped in single quotation marks Hello world
text2 = '\\Hello world\\' # The output is wrapped by two backslashes Hello world
print(text1)
print(text2)
Copy code
The following shows python Some of the escape characters in :
Escape character | describe |
---|---|
( When at the tail ) | Line continuation operator |
\ |
Backslash notation |
' |
Single quotation marks |
" |
Double quotes |
\a |
Ring the bell |
\b |
Backspace (Backspace) |
\000 |
empty |
\n |
Line break |
\v |
Vertical tabs |
\t |
Horizontal tabs |
\r |
enter |
\f |
Change the page |
\oyy |
Octal number ,yy Representative character , for example :\o12 On behalf of the line , among o It's the letters , Not numbers 0. |
\xyy |
Hexadecimal number ,yy Representative character , for example :\x0a On behalf of the line |
\other |
The other characters are output in normal format |
The original string is Python A special type of string in , In capital letters R
Or lowercase letters r
Start . In the original string , character “\
” No longer represents the meaning of escape characters .
The sample code is as follows :
text1 = " Those who made great achievements in ancient times ,\n It's not just super talent ,\n There must be perseverance "
text2 = r" Those who made great achievements in ancient times ,\n It's not just super talent ,\n There must be perseverance "
print(text1)
print(text2)
Copy code
Run the code as follows :
Those who made great achievements in ancient times ,
It's not just super talent ,
There must be perseverance
Those who made great achievements in ancient times ,\n It's not just super talent ,\n There must be perseverance
Copy code
Operation of string
Python There are many operators for string types
Splicing operator
Use +
Operator to realize string splicing , Use *
Operator to repeat the contents of a string
text1 = "Hello,world"
text2 = "!"
print(text1 + text2) # Hello,world!
print(text2 * 10) # !!!!!!!!!!
Copy code
use *
It is important to realize the repetition of strings , For example, to print a separation line, if it is written as ---------------
It's going to be a lot of trouble , But if you use - * 20
It's easy
Members of the operation
Python Can be used in the in
and not in
Determine whether there is another character or string in a string ,in
and not in
Operations are often called member operations , Will produce Boolean values True
or False
text1 = "Hello,world"
text2 = " A bowl week "
print("llo" in text1) # True
print(" Zhou " not in text2) # False
print(" porridge " not in text2) # True
Copy code
Get string length
With built-in functions len()
To get the length of characters
text1 = "Hello,world"
text2 = " A bowl week "
print(len(text1)) # 11
print(len(text2)) # 3
Copy code
Index and slice
If you reference a character in a string , You can index characters from ( notes :Python Of Index value from 0 At the beginning ), The operator is [n]
, among n
It's an integer , Suppose the length of the string is N
, that n
It can be from 0
To N-1
The integer of , among 0
Is the index of the first character in the string , and N-1
Is the index of the last character in the string , Usually called Forward index ; stay Python in , The index of the string can also be from -1
To -N
The integer of , among -1
Is the index of the last character , and -N
Is the index of the first character , Usually called Negative index .
It is worth noting that , because Strings are immutable types , therefore Characters in a string cannot be modified by index operation .
text1 = "Hello,world"
text2 = " A bowl week "
N1 = len(text1)
N2 = len(text2)
# Get the first character
print(text1[0], text1[-N1]) # H H
print(text2[0], text2[-N2]) # One One
# Get the last character
print(text1[N1 - 1], text1[-1]) # d d
print(text2[N2 - 1], text2[-1]) # Zhou Zhou
# Get the index as 2 and -2 The characters of
print(text1[2], text1[-2]) # l l
print(text2[2], text2[-2]) # Zhou bowl
Copy code
Be careful : If the index is out of bounds ( That is, the index value is not within the index range ) Can cause mistakes , for example
print(text2[222])
Copy code
The error message is as follows :
IndexError: string index out of range # ( The string index is out of range )
Copy code
If you want to take out multiple characters , To slice a string , The operator is [i:j:k]
, among i
It's the beginning of the index , The character corresponding to the index can't get N-1
perhaps -1
;j
It's the end index , The character corresponding to the index cannot be obtained 0
perhaps -N
;k
It's the step length , The default value is 1
, Represents a continuous slice of adjacent characters taken from front to back ( It can be omitted ), If k
The value of is a positive number , That is to say Forward index ; If k
The value of is negative , That is to say Negative index .
s = '123456789abcdef, A bowl week '
# i=3, j=6, k=1 Forward slicing operation
print(s[3:6]) # 456
# i=-17, j=-14, k=1 Forward slicing operation
print(s[-17:-14]) # 456
# i=16, j= Default , k=1 Forward slicing operation
print(s[16:]) # A bowl week
# i=-4, j= Default , k=1 Forward slicing operation
print(s[-3:]) # A bowl week
# i=8, j= Default , k=2 Forward slicing operation
print(s[8::2]) # 9bdf a week
# i=-12, j= Default , k=2 Forward slicing operation
print(s[-12::2]) # 8ace, bowl
# i= Default , j= Default , k=2 Forward slicing operation
print(s[::2]) # 13579bdf a week
# i= Default , j= Default , k=1 Forward slice of
print(s[:]) # 123456789abcdef, A bowl week
# i=1, j=-1, k=2 Forward slicing operation
print(s[1:-1:2]) # 2468ace, bowl
print("-"*20)
# i=7, j=1, k=-1 Negative slice operation
print(s[7:1:-1]) # 876543
# i=-13, j=-19, k=-1 Negative slice operation
print(s[-13:-19:-1]) # 876543
# i=8, j= Default , k=-1 Negative slice operation
print(s[8::-1]) # 987654321
# i= Default , j=1, k=-1 Negative slice operation
print(s[:15:-1]) # Zhou Wanyi
# i= Default , j= Default , k=-1 Negative slice of
print(s[::-1]) # Zhou Wanyi ,fedcba987654321
# i= Default , j= Default , k=-2 Negative slice of
print(s[::-2]) # Monday fdb97531
Copy code
i
The default value of is the first number ,j
The default value of is the end number ( Including itself )
It is worth noting that , The returned string includes i
barring j
Of .
String method
stay Python Use the methods of the type of string to process and operate the string , For a variable of string type , Use Variable name . Method name ()
To call its methods . The so-called method is actually a function bound to a certain type of variable .
Convert case
s1 = 'hello, world!'
# Use capitalize Method to obtain the string after the initial letter of the string is capitalized
print(s1.capitalize()) # Hello, world!
# Use title Method to get the string after the first letter of each word is capitalized
print(s1.title()) # Hello, World!
# Use upper Method to obtain the capitalized string
print(s1.upper()) # HELLO, WORLD!
s2 = 'GOODBYE'
# Use lower Method to obtain the lowercase string of the string
print(s2.lower()) # goodbye
Copy code
Search operation
If you want to find out whether there is another string from front to back in a string , You can use string find
or index
Method .
s = 'hello, world!'
# find Method to find the location of another string from the string
# Found the index of the first character of another string in the return string
print(s.find('or')) # 8
# No return found -1
print(s.find('shit')) # -1
# index Methods and find The method is similar to
# Found the index of the first character of another string in the return string
print(s.index('or')) # 8
# Exception thrown not found
print(s.index('shit')) # ValueError: substring not found
Copy code
In the use of find
and index
Method, you can also specify the search range through the parameters of the method , Just don't have to index 0
The position begins .``find and
index There are also reverse lookup methods ( Search back and forth ) Version of , Namely
rfind and
rindex`
s = 'hello good world!'
# Find characters from front to back o Position of appearance ( Equivalent to the first time )
print(s.find('o')) # 4
# From index to 5 Start looking for characters at the position of o Position of appearance
print(s.find('o', 5)) # 7
# Find characters from back to front o Position of appearance ( Equivalent to the last time )
print(s.rfind('o')) # 12
Copy code
Property judgment
You can use the of string startswith
、endswith
To determine whether a string starts and ends with a string ; You can also use is
The method at the beginning determines the characteristics of the string , These methods all return Boolean values .
s1 = 'hello, world!'
# startwith Method checks whether the string starts with the specified string and returns a Boolean value
print(s1.startswith('He')) # False
print(s1.startswith('hel')) # True
# endswith Method checks whether the string ends with the specified string and returns a Boolean value
print(s1.endswith('!')) # True
s2 = 'abc123456'
# isdigit Method checks whether the string is composed of numbers and returns a Boolean value
print(s2.isdigit()) # False
# isalpha Method checks whether the string is composed of letters and returns a Boolean value
print(s2.isalpha()) # False
# isalnum Method checks whether the string is composed of numbers and letters, and returns a Boolean value
print(s2.isalnum()) # True
Copy code
Formatted string
stay Python in , The string type can be through center
、ljust
、rjust
The method is to center 、 Left and right alignment processing .
s = 'hello, world'
# center Method in width 20 Center the string and fill it on both sides *
print(s.center(20, '*')) # ****hello, world****
# rjust Method in width 20 Align the string to the right and fill in spaces on the left
print(s.rjust(20)) # hello, world
# ljust Method in width 20 Align the string to the left and fill it on the right ~
print(s.ljust(20, '~')) # hello, world~~~~~~~~
Copy code
Python2.6 Start , Added a function to format strings str.format()
, It enhances string formatting .
The basic grammar is through {}
and :
To replace the old %
.
a = 111
b = 222
print('{0} + {1} = {2}'.format(a, b, a + b)) # 111 + 222 = 333
c = "hello"
d = "world"
# Does not set the specified location , By default
print("{} {}".format(c, d)) # hello world
print("{0} {1}".format(c, d)) # hello world
print("{1} {0}".format(d, c)) # hello world
print("{1} {0} {1}".format(c, d)) # world hello world
Copy code
from Python 3.6 Start , Format strings in a more concise way , Is to add... Before the string f
To format a string , In this way f
In the string beginning with ,{ Variable name }
It's a place holder , It will be replaced by the corresponding value of the variable .
a = 111
b = 222
print(f"{a} + {b} = {a + b}") # 111 + 222 = 333
c = "hello"
d = "world"
print(f"{c} {d}") # hello world
Copy code
Various operations on number formatting
Numbers | Format | Output | describe |
---|---|---|---|
3.1415926 | {:.2f} | 3.14 | Keep two decimal places |
3.1415926 | {:+.2f} | +3.14 | Keep two decimal places with symbols |
-1 | {:+.2f} | -1.00 | Keep two decimal places with symbols |
2.71828 | {:.0f} | 3 | Without decimals |
5 | {:0>2d} | 05 | Zero up the number ( Fill left , Width is 2) |
5 | {:x<4d} | 5xxx | Number complement x ( Fill the right side , Width is 4) |
10 | {:x<4d} | 10xx | Number complement x ( Fill the right side , Width is 4) |
1000000 | {:,} | 1,000,000 | Comma separated number format |
0.25 | {:.2%} | 25.00% | Percentage format |
1000000000 | {:.2e} | 1.00e+09 | Index notation |
13 | {:>10d} | 13 | Right alignment ( Default , Width is 10) |
13 | {:<10d} | 13 | Align left ( Width is 10) |
13 | {:^10d} | 13 | Align in the middle ( Width is 10) |
11 | '{:b}'.format(11)<br>'{:d}'.format(11) '{:o}'.format(11) '{:x}'.format(11)<br>'{:#x}'.format(11) '{:#X}'.format(11) |
1011<br> 11<br> 13<br>b<br>0xb<br>0XB |
Base number |
They're centered 、 Align left 、 Right alignment , Width of back band ,: Number followed by a filled character , It can only be one character , If it is not specified, it is filled with spaces by default .
+
Indicates that... Is displayed before a positive number +
, Display before negative number -
; ( Space ) Means adding a space before a positive number b、d、o、x They're binary 、 Decimal system 、 octal 、 Hexadecimal .
Trim operation
strip()
Method is used to remove the original string and trim the left and right specified characters ( The default is space or newline ) Or character sequence . This method is of great practical value , It is usually used to remove the leading and trailing spaces in user input because of careless typing ,strip
There are ways lstrip
( namely left strip
) and rstrip
( namely right strip
) Two versions .
s = ' A bowl week \t\n'
# strip Method to obtain the string after trimming the left and right spaces of the string
print(s.strip()) # A bowl week
s1 = "!!! A bowl week !!!"
print(s1.lstrip("!")) # A bowl week !!!
print(s1.rstrip("!")) # !!! A bowl week
Copy code
copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301043492514.html
The sidebar is recommended
- Python Network Programming -- create a simple UPD socket to realize mutual communication between two processes
- leetcode 110. Balanced Binary Tree(python)
- Django uses Django celery beat to dynamically add scheduled tasks
- The bear child said "you haven't seen Altman" and hurriedly studied it in Python. Unexpectedly
- Optimization iteration of nearest neighbor interpolation and bilinear interpolation algorithm for Python OpenCV image
- Bilinear interpolation algorithm for Python OpenCV image, the most detailed algorithm description in the whole network
- Use of Python partial()
- Python game development, pyGame module, python implementation of angry birds
- leetcode 1104. Path In Zigzag Labelled Binary Tree(python)
- Save time and effort. 10 lines of Python code automatically clean up duplicate files in the computer
guess what you like
-
Learn python, know more meat, and be a "meat expert" in the technical circle. One article is enough
-
[Python data structure series] "stack (sequential stack and chain stack)" -- Explanation of knowledge points + code implementation
-
Datetime module of Python time series
-
Python encrypts and decrypts des to solve the problem of inconsistency with Java results
-
Chapter 1: introduction to Python programming-4 Hello World
-
Summary of Python technical points
-
11.5K Star! An open source Python static type checking Library
-
Chapter 2: Fundamentals of python-1 grammar
-
[Python daily homework] day4: write a function to count the number of occurrences of each number in the incoming list and return the corresponding dictionary.
-
Python uses turtle to express white
Random recommended
- Some people say Python does not support function overloading?
- "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system with Python
- Introduction to Python - CONDA common commands
- Python actual combat | just "4 steps" to get started with web crawler (with benefits)
- Don't know what to eat every day? Python to tell you! Generate recipes and don't worry about what to eat every day!
- Are people who like drinking tea successful? I use Python to make a tea guide! Do you like it?
- I took 100g pictures offline overnight with Python just to prevent the website from disappearing
- Binary operation of Python OpenCV image re learning and image smoothing (convolution processing)
- Analysis of Python event mechanism
- Iterator of Python basic language
- Base64 encryption and decryption in Python
- Chapter 2: Fundamentals of python-2 variable
- Python garbage collection summary
- Python game development, pyGame module, python takes you to realize a magic tower game from scratch (1)
- Python draws a spinning windmill with turtle
- Deep understanding of Python features
- A website full of temptations for Python crawler writers, "lovely picture network", look at the name of this website
- Python opencv Canny edge detection knowledge supplement
- Complex learning of Python opencv Sobel operator, ScHARR operator and Laplacian operator
- Python: faker extension package
- Python code reading (Part 44): find the location of qualified elements
- Elegant implementation of Django model field encryption
- 40 Python entry applet
- Pandas comprehensive application
- Chapter 2: Fundamentals of python-3 character string
- Python pyplot draws a parallel histogram, and the x-axis value is displayed in the center of the two histograms
- [Python crawler] detailed explanation of selenium from introduction to actual combat [1]
- Curl to Python self use version
- Python visualization - 3D drawing solutions pyecharts, Matplotlib, openpyxl
- Use python, opencv's meanshift and CAMSHIFT algorithms to find and track objects in video
- Using python, opencv obtains and changes pixels, modifies image channels, and trims ROI
- [Python data collection] university ranking data collection
- [Python data collection] stock information collection
- Python game development, pyGame module, python takes you to realize a magic tower game from scratch (2)
- Python solves the problem of suspending execution after clicking the mouse in CMD window (fast editing mode is prohibited)
- [Python from introduction to mastery] (II) how to run Python? What are the good development tools (pycharm)
- Python type hints from introduction to practice
- Python notes (IX): basic operation of dictionary
- Python notes (8): basic operations of collections
- Python notes (VII): definition and use of tuples