[Introduction to Python] How to split a character string with the split function

[Introduction to Python] How to split a character string with the split function

The split function separates and lists character strings that are a mixture of numbers, alphabets, symbols, etc., according to a certain rule. Writing a program that separates strings from scratch can be very cumbersome, and for beginners it can be a daunting task that can take a day if you're not good at writing it. The Split function is a very convenient function that frees you from such complexity. Just knowing this will change your work efficiency considerably.

table of contents 1 [Basic usage of split function](## Basic usage of split function) 2 [Application of delimiter](## Application of delimiter) 3 [rsplit function](## rsplit function)

Basic usage of split function

For example, consider the case where the data you created is separated by "," as shown below.

>>> print test
orange,apple,banana,strawberry

You can get a list separated by a delimiter by using the string name .split (“delimiter”).

>>> test.split(",") #The list called test is delimited by ",Separated by
['orange', 'apple', 'banana', 'strawberry']

Also, when the delimiter is a space, line feed, or tab, you can separate it without specifying a delimiter.

>>> test = "orange apple banana strawberry"
>>> test.split() #If nothing is specified in the argument, it will be automatically separated by spaces or tabs.
['orange', 'apple', 'banana', 'strawberry']

If you use this, for example, even if there are two spaces in the delimiter, you can divide it neatly.

>>> test = "2016  November  15" #It is separated by two spaces.
>>> test.split() # 
['2016', 'November', '15'] 

Even if there are multiple delimiters between the characters you want to divide in this way, you can easily handle it with this.

Advanced version of how to separate

Furthermore, if you want to do something crowded, for example, "Separate up to the second, do not separate the third and subsequent ones", you can do as follows.

>>> test = "orange,apple,banana,strawberry"
>>> test.split(",", 2) #Divide up to the second time, and do not divide after the third time.
['orange', 'apple', 'banana,strawberry']

Then, what if you want to separate only the first one without specifying the delimiter? For example, when I tried the following, I got an error.

>>> test = "2016  November  15" #It is separated by two spaces.
>>> test.split(1) #I wanted to separate only the first one. .. ..
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a character buffer object

In Python terms, the first argument of the split function seems to be useless without a delimiter.

In this case, None is used to mean "the user does not explicitly specify the delimiter".

>>> test = "2016  November  15" #It is separated by two spaces.
>>> test.split(None,1)
['2016', 'November  15']

By doing this, I was able to successfully divide only the first one.

rsplit function

We will also introduce the rsplit function, which has a sister relationship with the split function. rsplit is basically the same as split. However, split has a delimiter order from the beginning of the string, while rsplit has a delimiter order from the end of the string. As an aside, the "r" in rsplit seems to come from right, which means from the right side of the string, or rear, which means after.

Let's actually go.

>>> test = "orange,apple,banana,strawberry"
>>> test.rsplit(",") # “,Separate with ”. There is no limit to the number of divisions.
['orange', 'apple', 'banana', 'strawberry']

If only the delimiter is given to the argument of rsplit in this way, the rsplit function = split function. Now, add the number of delimiters as an argument (= 2).

>>> test = "orange,apple,banana,strawberry"
>>> test.rsplit(",",2)
['orange,apple', 'banana', 'strawberry']

You can see that the second from the back is certainly separated.

Furthermore, the delimiter does not have to be one character. Strings are perfectly fine and the split and rsplit functions work.

>>> test = "orangehogeapplehogebananahogestrawberry" 
>>> test.split("hoge")  #The string hoge corresponds to the delimiter
['orange', 'apple', 'banana', 'strawberry']

Recommended Posts

[Introduction to Python] How to split a character string with the split function
[Introduction to Python] How to write a character string with the format function
[Introduction to Python] How to iterate with the range function?
[Python] How to invert a character string
[Introduction to Python] How to get data with the listdir function
[Introduction to Python] How to output a character string in a Print statement
[Python] Explains how to use the range function with a concrete example
[Introduction to Python] How to sort the contents of a list efficiently with list sort
How to convert / restore a string with [] in python
[Python] How to expand variables in a character string
I want to split a character string with hiragana
[Introduction to Python] How to get the index of data with a for statement
Python learning basics ~ How to output (display) a character string? ~
[Python 3.8 ~] How to define a recursive function smartly with a lambda expression
Try to extract a character string from an image with Python3
[Introduction to Python] How to use the in operator in a for statement?
[Python] Explains how to use the format function with an example
How to extract the desired character string from a line 4 commands
How to send a request to the DMM (FANZA) API with python
How to quickly count the frequency of appearance of characters from a character string in Python?
How to read a CSV file with Python 2/3
How to embed a variable in a python string
Introduction to Python with Atom (on the way)
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
[Introduction to Python] Thorough explanation of the character string type used in Python!
How to delete the specified string with the sed command! !! !!
[Python] How to draw a line graph with Matplotlib
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
How to create a submenu with the [Blender] plugin
How to call a function
[Python] How to specify the download location with youtube-dl
# Function that returns the character code of a string
[Tentative] How to convert a character string to Shift_jis with kivy-ios Memo kivy v1.8.0
[Introduction to Udemy Python3 + Application] 27. How to use the dictionary
[Introduction to Udemy Python3 + Application] 30. How to use the set
[Introduction to Python] How to stop the loop using break?
[Python] How to rewrite the table style with python-pptx [python-pptx]
[Python] I tried to get the type name as a string from the type function
[Python] How to create a 2D histogram with Matplotlib
[Python] How to call a c function from python (ctypes)
How to input a character string in Python and output it as it is or in the opposite direction.
[Python] How to draw a scatter plot with Matplotlib
How to get a list of files in the same directory with python
How to identify the element with the smallest number of characters in a Python list?
I tried to automatically generate a character string to be input to Mr. Adjustment with Python
[Python] Leave only the elements that start with a specific character string in the array
How to unit test a function containing the current time using freezegun in python
I tried to simulate how the infection spreads with Python
How to install NPI + send a message to line with python
How to convert an array to a dictionary with Python [Application]
Create a Mastodon bot with a function to automatically reply with Python
How to use the __call__ method in a Python class
Probably the easiest way to create a pdf with Python3
How to print characters as a table with Python's print function
How to get the last (last) value in a list in Python
A story about how to deal with the CORS problem
How to build a python2.7 series development environment with Vagrant
How to get into the python development environment with Vagrant
[Python] The first step to making a game with Pyxel
Create a message corresponding to localization with python translation string
How to connect the contents of a list into a string