[Python] Summary of how to use split and join functions

[Python] Summary of how to use split and join functions

  1. [split function](#split function)
  2. [Split by blank (empty argument)](#Split by blank)
  3. [Split by specified character](# Split by specified character)
  4. [Specify the number of delimiters](#Specify the number of delimiters)
  5. [rsplit function](#rsplit function)
  6. [join function](#join function)
  7. [Combine string list (default)](# Combine string list by default)
  8. [Combine list of numbers](# Combine list of numbers)

split function

Divide the character string by the specified characters to make a list.

Object .split ("split character ") └ Characters in the argument are deleted └ Object is a character string * Numerical value is an error └ Not destructive * The original object remains as it is └ If the argument is empty, split it with a space


### Split with whitespace

Split with whitespace


s="1 2 3 4 5 6"

l = s.split()
print(l)

#output
['1', '2', '3', '4', '5', '6']

Specify a space as an argument


s="1 2 3 4 5 6"

l = s.split(" ")
print(l)

#output
['1', '2', '3', '4', '5', '6']

### error An error will occur if you split anything other than a character string.

error


i=123456
l = i.split()

AttributeError: 'int' object has no attribute 'split'

### Split by specified character

python


s="1,2,3,4,5,6"
l = s.split(",")
print(l)

#output
['1', '2', '3', '4', '5', '6']

text


s="I have a pen !"
l = s.split()
print(l)

#output
['I', 'have', 'a', 'pen', '!']

Delimiter removed


s="I have a pen !"
l = s.split("a")
print(l)

#output
['I h', 've ', ' pen !']

### Specify the number to separate If you pass an integer as the second argument, that number will be the maximum number of delimiters.

split ('separator', integer) └ Divide into integers └ Maximum index number becomes an integer

python


s="1 2 3 4 5 6"
l = s.split(" ",2)
print(l)

#output
['1', '2', '3 4 5 6']

Element specification


s="1 2 3 4 5 6"
l = s.split(" ",2)

print(l[0])
print(l[2])

#output
1
3 4 5 6

Output the 0th element and the 2nd element. l [3] is out of range (IdexError: list index out of range)


### rsplit function ** Separate from the back ** by the number specified by the second argument.

rsplit ('separator', integer) └ Separate from the back by an integer └ Maximum index number becomes an integer

python


s="1 2 3 4 5 6"

ls = s.split(" ", 2)
lr = s.rsplit(" ", 2)
print(ls)
print(lr)

#output
['1', '2', '3 4 5 6']
['1 2 3 4', '5', '6']  #rsplit separates from behind

Extracting elements


s="1 2 3 4 5 6"

ls = s.split(" ", 2)
lr = s.rsplit(" ", 2)

#Output the 0th element
print(ls[0])
print(lr[0])

#output
1
1 2 3 4

** ▼ If not separated, the output will be the same as the split function **

No number of delimiters specified


s="1 2 3 4 5 6"

ls = s.split()
lr = s.rsplit()
print(ls)
print(lr)

#output
['1', '2', '3', '4', '5', '6']
['1', '2', '3', '4', '5', '6']

## join function Combines a list of strings whose elements are strings with the specified characters.

'Join character'.join (list) └ The element of list is a character string └ An error will occur if the element is not a character string └ Not destructive (object remains intact)

Combine list of strings (default)

python


l = ['I', 'have', 'a', 'pen', '!']

#「-Combine with
s1 = "-".join(l)
print(s1)

#Combine with whitespace
s2 = " ".join(l)
print(s2)

#output
I-have-a-pen-!
I have a pen !

** ▼ An error will occur if the element is not a character string **

python


l=[1,2,3,4]
s = "-".join(l)

#output
TypeError: sequence item 0: expected str instance, int found

### Combine list of numbers

(1) Convert to a character string with the map function. (2) Convert to a character string with a for statement.

(1) Convert to a character string with the map function

Convert elements from numbers to strings with the map function and join them with join.

python


l=[1,2,3,4]

ls = map(str, l)
s = "-".join(ls)
print(s)

#output
1-2-3-4

** ▼ What is the map function **

map (processing, iterable) -Perform processing one for each element of iterable. -If you specify a type for processing, you can convert to that type. -Output is map type (example: <map at 0x2d00fce8b80>) ・ Not destructive.

** ▼ Convert to a character string with map ** map (str, iterable)

Convert the numbers in list to strings


l=[1,2,3,4]

s = map(str, l)
print(list(s))

#output
['1', '2', '3', '4']

#### (2) Convert to a character string with a for statement Extract the elements of list one by one and convert them to str type.

python


l=[1,2,3,4]

s = "-".join([str(i) for i in l])
print(s)

#output
1-2-3-4

・ Inclusive notation [Processing for Variables in Iterable] └ The processing result is returned as a list.

Recommended Posts

[Python] Summary of how to use split and join functions
[Python] Summary of how to use pandas
[Python2.7] Summary of how to use unittest
Summary of how to use Python list
[Python2.7] Summary of how to use subprocess
Comparison of how to use higher-order functions in Python 2 and 3
Summary of how to use MNIST in Python
Summary of how to use pandas.DataFrame.loc
Summary of how to use pyenv-virtualenv
Summary of how to use csvkit
[python] Summary of how to retrieve lists and dictionary elements
How to install and use pandas_datareader [Python]
python: How to use locals () and globals ()
How to use Python zip and enumerate
[Python] Understand how to use recursive functions
How to use is and == in Python
[Question] How to use plot_surface of python
Summary of how to import files in Python 3
[Python] How to use hash function and tuple.
Summary of studying Python to use AWS Lambda
python3: How to use bottle (2)
How to use Python argparse
Python: How to use pydub
[Python] How to use checkio
[Python] How to use input ()
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
I tried to summarize how to use matplotlib of python
How to use Python Kivy ① ~ Basics of Kv Language ~
[Python] How to split and modularize files (simple, example)
[Python] Summary of how to specify the color of the figure
Summary of how to share state with multiple functions
[Python] Summary of eval / exec functions + How to write character strings with line breaks
How to install and use Tesseract-OCR
[Python] How to use Pandas Series
How to use Requests (Python Library)
How to use SQLite in Python
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
[Introduction to Python] Summary of functions and methods that frequently appear in Python [Problem format]
How to use .bash_profile and .bashrc
How to install and use Graphviz
[Python] How to use list 3 Added
How to use Mysql in python
How to use OpenPose's Python API
How to use ChemSpider in Python
How to use FTP with Python
[Introduction to Data Scientists] Basics of Python ♬ Functions and classes
Python: How to use pydub (playback)
How to use PubChem in Python
Introduction of DataLiner ver.1.3 and how to use Union Append
How to use python zip function
[Python] How to use Typetalk API
Summary of Python indexes and slices
Overview of Python virtual environment and how to create it
[Introduction to statistics] What kind of distribution is the t distribution, chi-square distribution, and F distribution? A little summary of how to use [python]
[Python] How to get the first and last days of the month
How to use Python Kivy (reference) -I translated Kivy Language of API reference-
How to use Serverless Framework & Python environment variables and manage stages