[Learn python from zero] 13. Common operations on Python strings (1)

String Common Operations

Common operations on strings include:

  • Get length:len
  • Find what: find, index, rfind,rindex
  • Judgment: startswith, endswith, isalpha, isdigit, isalnum,isspace
  • Count occurrences:count
  • Replacement content:replace
  • Cut string: split, rsplit, splitlines, partition,rpartition
  • Modify case: capitalize, title, upper,lower
  • Space handling: ljust, rjust, center, lstrip, rstrip,strip
  • String concatenation:join

Note: In Python, strings are immutable! All string-related methods will not change the original string, but return a result. In this new return value, the result after execution is retained!


len

lenfunction to get the length of a string.

mystr = '今天天气好晴朗,处处好风光呀好风光'
print(len(mystr))  # 17 获取字符串的长度

look up

Find related methods, which are used in roughly the same way, but with slight differences.

1. find

Find whether the specified content exists in the string, if it exists, return the starting position index value of the first occurrence of the content in the string, if not, return -1.

Grammar format:

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

Example:

mystr = '今天天气好晴朗,处处好风光呀好风光'
print(mystr.find('好风光'))  # 10 '好风光'第一次出现时,'好'所在的位置
print(mystr.find('你好'))  # -1  '你好'不存在,返回 -1
print(mystr.find('风', 12))  # 15 从下标12开始查找'风',找到风所在的位置试15
print(mystr.find('风光',1,10)) # -1 从下标1开始到12查找"风光",未找到,返回 -1

2. rfind

Similar to find()the function, but searches from the right.

mystr = '今天天气好晴朗,处处好风光呀好风光'
print(mystr.rfind('好')) # 14

3. index

Same as find()the method, except that when the find method is not found, -1 is returned, and when str is not found, an exception will be reported.

Grammar format:

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

4. rindex

Similar index(), but starts from the right.


judgment

Python provides a very rich method that can be used to judge a string.

1. startswith

Determine whether the string starts with the specified content.

Grammar format:

S.startswith(prefix[, start[, end]]) -> bool

Example:

mystr = '今天天气好晴朗,处处好风光呀好风光'
print(mystr.startswith('今'))  # True
print(mystr.startswith('今日')) # False

2. endswith

Determine whether the string ends with the specified content.

mystr = '今天天气好晴朗,处处好风光呀好风光"
print(mystr.endswith("风光"))  # True
print(mystr.endswith("好风光"))  # False

#### 3. isalpha

判断字符串是否全是字母字符。

```python
mystr = 'Hello'
print(mystr.isalpha())  # True

mystr = 'Hello123'
print(mystr.isalpha())  # False

4. also

Determines whether a string is full of numeric characters.

mystr = '12345'
print(mystr.isdigit())  # True

mystr = '123abc'
print(mystr.isdigit())  # False

5. the ice room

Determines whether a string is all alpha or numeric characters.

mystr = 'Hello123'
print(mystr.isalnum())  # True

mystr = 'Hello!123'
print(mystr.isalnum())  # False

6. isspace

Determines whether a string is full of space characters.

mystr = '    '
print(mystr.isspace())  # True

mystr = ' Hello '
print(mystr.isspace())  # False


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/132232239