Article directory
count
Returns the number of occurrences str
in between start
and .end
mystr
Grammar format:
S.count(sub[, start[, end]]) -> int
Example:
mystr = '今天天气好晴朗,处处好风光呀好风光'
print(mystr.count('好')) # 3. '好' 字出现三次
replace
Replaces what is specified in the string, count
up to count
times if specified.
mystr = '今天天气好晴朗,处处好风光呀好风光'
newstr = mystr.replace('好', '坏')
print(mystr) # 今天天气好晴朗,处处好风光呀好风光 原字符串未改变!
print(newstr) # 今天天气坏晴朗,处处坏风光呀坏风光 得到的新字符串里,'好' 被修改成了 '坏'
newstr = mystr.replace('好', '坏', 2) # 指定了替换的次数
print(newstr) # 今天天气坏晴朗,处处坏风光呀好风光 只有两处的 '好' 被替换成了 '坏'
content separation
Content separation mainly involves four methods of split
, splitlines
, partition
and .rpartition
split
Slice with the specified string as the delimiter, and if maxsplit
has the specified value, only maxsplit+1
substrings will be separated. The returned result is a list.
mystr = '今天天气好晴朗,处处好风光呀好风光'
result = mystr.split() # 没有指定分隔符,默认使用空格,换行等空白字符进行分隔
print(result) # ['今天天气好晴朗,处处好风光呀好风光'] 没有空白字符,所以,字符串未被分隔
result = mystr.split('好') # 以 '好' 为分隔符
print(result) # ['今天天气', '晴朗,处处', '风光呀', '风光']
result = mystr.split("好", 2) # 以 '好' 为分隔符,最多切割成 3 份
print(result) # ['今天天气', '晴朗,处处', '风光呀好风光']
rsplit
The usage is split
basically the same as that of , except that they are separated from right to left.
mystr = '今天天气好晴朗,处处好风光呀好风光'
print(mystr.rsplit('好', 1)) # ['今天天气好晴朗,处处好风光呀', '风光']
split lines
Separated by line, return a list containing each line as an element.
mystr = 'hello \nworld'
print(mystr.splitlines())
partition
Divide mystr
with str
into three parts, str
before, str
and str
after, the three parts form a tuple.
mystr = '今天天气好晴朗,处处好风光呀好风光'
print(mystr.partition('好')) # ('今天天气', '好', '晴朗,处处好风光呀好风光')
rpartition
Similar to partition()
the function, but starts from the right.
mystr = '今天天气好晴朗,处处好风光呀好风光'
print(mystr.rpartition('好')) # ('今天天气好晴朗,处处好风光呀', '好', '风光')
Modify capitalization
The function of modifying capitalization is only valid for English, mainly including capitalizing the first letter capitalize
, capitalizing the first letter of each word title
, all lowercase lower
, and all uppercase upper
.
capitalize
Capitalize the first letter of the first word.
mystr = 'hello world'
print(mystr.capitalize()) # Hello world
title
Capitalize the first letter of each word.
mystr = 'hello world'
print(mystr.title()) # Hello World
lower
All become lowercase.
mystr = 'hElLo WorLD'
print(mystr.lower()) # hello world
upper
All become uppercase.
mystr = 'hello world'
print(mystr.upper()) # HELLO WORLD
Space handling
Python provides us with various methods for manipulating tables in strings.
1. ljust
Returns a string of the specified length, padded on the right with blank characters (left justified).
str = 'hello'
print(str.ljust(10)) # hello 在右边补了五个空格
2. rjust
Returns a string of the specified length, padded on the left with blank characters (right justified).
str = 'hello'
print(str.rjust(10)) # hello在左边补了五个空格
3. center
Returns a string of the specified length, with whitespace padding at both ends (center-aligned).
str = 'hello'
print(str.center(10)) # hello 两端加空格,让内容居中
4. lstrip
Remove mystr
whitespace characters to the left.
mystr = ' he llo '
print(str.lstrip()) # he llo 只去掉了左边的空格,中间和右边的空格被保留
5. rstrip
Remove mystr
whitespace characters to the right.
mystr = ' he llo '
print(str.rstrip()) # he llo右边的空格被删除
6. strip
Removes two breaking whitespace characters.
str = ' he llo '
print(str.strip()) # he llo
string concatenation
Traverse the parameters, take out each item in the parameter, and then add it later mystr
.
Grammar format:
S.join(iterable)
Example:
mystr = 'a'
print(mystr.join('hxmdq')) # haxamadaq 把 hxmd 一个个取出,并在后面添加字符 a. 最后的 q 保留,没有加 a
print(mystr.join(['hi', 'hello', 'good'])) # hiahelloagood
Function: You can quickly convert a list or tuple into a string and separate it with specified characters.
txt = '_'
print(txt.join(['hi', 'hello', 'good'])) # hi_hello_good
print(txt.join(('good', 'hi', 'hello'))) # good_hi_hello
string operators
The addition operator can be used between strings to concatenate two strings into one string. For example: 'hello' + 'world'
the result of is 'helloworld'
.
Multiplication can be done between strings and numbers, and the result is to repeat the specified string multiple times. For example: 'hello' * 2
the result of is 'hellohello'
.
Between strings, if a comparison operator is used for calculation, the code corresponding to the character will be obtained and then compared.
In addition to the above-mentioned operators, strings do not support other operators by default.
Advanced case
[Python] Python realizes the word guessing game-challenge your intelligence and luck!
[python] Python tkinter library implements GUI program for weight unit converter
[python] Use Selenium to get (2023 Blog Star) entries
Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition
[Xiaobai must see] Python word cloud generator detailed analysis and code implementation
[Xiaobai must see] Python crawls an example of NBA player data
[Must-see for Xiaobai] Sample code for crawling and saving Himalayan audio using Python
[Xiaobai must see] Python crawler data processing and visualization
[Must-see for Xiaobai] Python crawler program to easily obtain hero skin pictures of King of Glory
[Must-see for Xiaobai] Use Python to generate a personalized list Word document
Geospatial data processing and visualization using geopandas and shapely (.shp)
Use selenium to crawl Maoyan movie list data
Detailed explanation of the principle and implementation of image enhancement algorithm Retinex
Getting Started Guide to Crawlers (8): Write weather data crawler programs for visual analysis
Getting started with crawlers (4): The best way to crawl dynamic web pages using Selenium and API
Getting Started Guide to Crawlers (3): Python network requests and common anti-crawler strategies
Getting started with crawlers (2): How to use regular expressions for data extraction and processing
Getting started with reptiles (1): Learn the basics and skills of reptiles
Python object-oriented programming basics and sample code
MySQL database operation guide: learn how to use Python to add, delete, modify and query operations
Python file operation guide: encoding, reading, writing and exception handling
Selenium Automation Toolset - Complete Guide and Tutorials
Python web crawler basics advanced to actual combat tutorial
Pandas data processing and analysis tutorial: from basics to actual combat
Detailed explanation of commonly used data types and related operations in Python
[Latest in 2023] Detailed Explanation of Six Major Schemes to Improve Index of Classification Model