


Detailed explanation of how to use strip() and split() in python
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】
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!

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.

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

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

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)

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.

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

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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 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
God-level code editing software (SublimeText3)

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
Integrate Eclipse with SAP NetWeaver application server.
