[Learn python from zero] 14. Common operations on Python strings (2)

count

Returns the number of occurrences strin between startand .endmystr

Grammar format:

S.count(sub[, start[, end]]) -> int

Example:

mystr = '今天天气好晴朗,处处好风光呀好风光'
print(mystr.count('好'))  # 3. '好' 字出现三次

replace

Replaces what is specified in the string, countup to counttimes 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, partitionand .rpartition

split

Slice with the specified string as the delimiter, and if maxsplithas the specified value, only maxsplit+1substrings 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 splitbasically 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 mystrwith strinto three parts, strbefore, strand strafter, 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 mystrwhitespace characters to the left.

mystr = '    he   llo      '
print(str.lstrip())  # he   llo      只去掉了左边的空格,中间和右边的空格被保留

5. rstrip

Remove mystrwhitespace 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' * 2the 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

[python] Use Selenium and Chrome WebDriver to obtain article information in [Tencent Cloud Studio Practical Training Camp]

Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition

[Fun with Python series [Xiaobai must see] Python multi-threaded crawler: download pictures of emoticon package websites

[Play with Python series] [Must-see for Xiaobai] Use Python to crawl historical data of Shuangseqiu and analyze it visually

[Play with python series] [Must-see for Xiaobai] Use Python crawler technology to obtain proxy IP and save it to a file

[Must-see for Xiaobai] Python image synthesis example using PIL library to realize the synthesis of multiple images by ranks and columns

[Xiaobai must see] Python crawler actual combat downloads pictures of goddesses in batches and saves them locally

[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

[Must-see for Xiaobai] Technical realization of using Python to download League of Legends skin pictures in batches

[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

[Must-see for Xiaobai] Python crawler combat: get pictures from Onmyoji website and save them automatically

Xiaobai must-see series of library management system - sample code for login and registration functions

100 Cases of Xiaobai's Actual Combat: A Complete and Simple Shuangseqiu Lottery Winning Judgment Program, Suitable for Xiaobai Getting Started

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

Introductory Guide to Crawlers (7): Using Selenium and BeautifulSoup to Crawl Douban Movie Top250 Example Explanation [Reptile Xiaobai must watch]

Getting Started Guide to Crawlers (6): Anti-crawlers and advanced skills: IP proxy, User-Agent disguise, Cookie bypass login verification and verification code identification tools

Introductory Guide to Crawlers (5): Distributed Crawlers and Concurrency Control [Implementation methods to improve crawling efficiency and request rationality control]

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

Application of Deep Learning Model in Image Recognition: CIFAR-10 Dataset Practice and Accuracy Analysis

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

Use Python and Selenium to automate crawling#【Dragon Boat Festival Special Call for Papers】Explore the ultimate technology, and the future will be due to you"Zong" #Contributed articles

Python multi-thread and multi-process tutorial: comprehensive analysis, code cases and optimization skills

Selenium Automation Toolset - Complete Guide and Tutorials

Python web crawler basics advanced to actual combat tutorial

Python introductory tutorial: master the basic knowledge of for loop, while loop, string operation, file reading and writing and exception handling

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

Introductory Python programming basics and advanced skills, web development, data analysis, and machine learning and artificial intelligence

Graph prediction results with 4 regression methods: Vector Regression, Random Forest Regression, Linear Regression, K-Nearest Neighbors Regression

Guess you like

Origin blog.csdn.net/qq_33681891/article/details/132232658