search
HomeBackend DevelopmentPython TutorialDetailed explanation of how to use strip() and split() in python

Detailed explanation of how to use strip() and split() in python

May 18, 2017 pm 02:31 PM
pythonsplit()strip()andfunction

This article mainly introduces the detailed explanation and examples of the python strip() function and split() function. Friends in need can refer to

python strip() function and split( ) Detailed explanation and examples of functions

I have never been able to distinguish the functions of strip and split. In fact, strip means delete; and split means splitting. Therefore, it also means that the two functions are completely different. Strip can delete certain characters of string, while split splits the string according to the specified characters. Let’s talk about these two functions in detail below.

1 Python strip() function introduction

Function prototype

Declaration: s is a string, rm is the character sequence to be deleted

s.strip(rm) Delete the characters at the beginning and end of the s string, located in the rm deletion sequence

s.lstrip(rm) Delete the s character The character at the beginning of the string, located in the rm deletion sequence

s.rstrip(rm) Delete the character at the end of the s string, located in the rm deletion sequence

Note:

(1) When rm is empty, whitespace characters (including '\n', '\r', '\t', ' ') are deleted by default.

(2)Here The rm deletion sequence is to delete the characters on the edge (beginning or end) as long as they are within the deletion sequence.

For example,

>>> a = '  123' 
>>> a 
'  123' 
>>> a.strip() 
'123'

(2) The rm deletion sequence here is to delete the characters on the edge (beginning or end) as long as they are within the deletion sequence.

For example,

>>> a = '123abc' 
>>> a.strip('21') 
'3abc' 
>>> a.strip('12') 
'3abc'

The result is the same.

2 python split() function introduction

Explanation:

There is no character type in Python In other words, there is only the string . The character mentioned here is a string containing only one character! ! !

The reason why it is written like this is just for the convenience of understanding, nothing more.

(1) Split by a certain character, such as '.'

>>> str = ('www.google.com') 
>>> print str 
www.google.com 
>>> str_split = str.split('.') 
>>> print str_split 
['www', 'google', 'com']

(2) Split by a certain character, and split n times. For example, press '.' to split once

>>> str_split = str.split('.',1) 
>>> print str_split 
['www', 'google.com']

(3) You can also add regular expression after the split() function, for example:

>>> str_split = str.split('.')[0] 
>>> print str_split 
www

after split is a List, [0] means taking the first element;

>>> str_split = str.split('.')[::-1] 
>>> print str_split 
['com', 'google', 'www'] 
>>> str_split = str.split('.')[::] 
>>> print str_split 
['www', 'google', 'com']

Arrange in reverse order, [::] Arrange in positive order

>>> str = str + '.com.cn' 
>>> str 
'www.google.com.com.cn' 
>>> str_split = str.split('.')[::-1] 
>>> print str_split 
['cn', 'com', 'com', 'google', 'www'] 
>>> str_split = str.split('.')[:-1] 
>>> print str_split 
['www', 'google', 'com', 'com']

From the first element to the end, the last one The element is deleted.

One of the typical applications of the split() function, ip number exchange:

# ip ==> number

>>> ip2num = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])]) 
>>> ip2num('192.168.0.1') 
3232235521

# number ==> ip # number range [0, 255^4]

>>> num2ip = lambda x: '.'.join([str(x/(256**i)%256) for i in range(3,-1,-1)]) 
>>> num2ip(3232235521) 
'192.168.0.1'

Finally, how does Python convert an integer to an IP address?

>>> import socket 
>>> import struct 
>>> int_ip = 123456789 
>>> socket.inet_ntoa(struct.pack(‘I',socket.htonl(int_ip)))#整数转换为ip地址 
‘7.91.205.21' 
>>> str(socket.ntohl(struct.unpack(“I”,socket.inet_aton(“255.255.255.255″))[0]))#ip地址转换为整数 
‘4294967295'

【Related recommendations】

1. Python free video tutorial

2. Detailed explanation of the usage scenarios of strip function in python

3. The little-known traps of strip() in python

4. The wonderful uses of strip() function in Python that you don’t know

5. Basic introduction to python teaches you how to use the strip() function to remove spaces\n\r\t

The above is the detailed content of Detailed explanation of how to use strip() and split() in python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

What is a lambda function?What is a lambda function?Apr 28, 2025 pm 04:28 PM

Article discusses lambda functions, their differences from regular functions, and their utility in programming scenarios. Not all languages support them.

What is a break, continue and pass in Python?What is a break, continue and pass in Python?Apr 28, 2025 pm 04:26 PM

Article discusses break, continue, and pass in Python, explaining their roles in controlling loop execution and program flow.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.