String split in Python

days_64

Python64

Posted on March 4, 2020

String split in Python

In this article we simply talk about two methods of text parsing in Python. What we will do is given a string like

>>> line = 'aaa bbb ccc'

Split it into substrings, create strings based on this string.

Slice string

The first method is fragment by fragment. Define the recording offset, and then extract the desired string. [start:end]. Example:

>>> line = 'aaa bbb ccc'
>>> col1 = line[0: 3]
>>> col3 = line[8:]
>>> col1
'aaa'
>>> col3
'ccc'
>>>

However, this is undoable with a large string. Many developers use the .split () function.

Split function

The split() function turns a string into a list of strings. By default this function splits on spaces, meaning every word in a sentence will be a list item.

>>> line = 'aaa bbb ccc'
>>> a = line.split ( '')
>>> a
[ 'Aaa', 'bbb', 'ccc']
>>> a[0]
'Aaa'
>>> a[1]
'Bbb'
 >>> a[2]
'Ccc'
 >>>

You can split on character in the string, by setting the character in the split function. This can be a comma, a dash, a semicolon or even a dot (phrases).

>>> line = 'aaa, bbb, ccc'
>>> a = line.split(',')
>>> a
[ 'Aaa', 'bbb', 'ccc']
>>>
💖 💪 🙅 🚩
days_64
Python64

Posted on March 4, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning Python
javascript Learning Python

November 28, 2024

Calculate savings with Python!
beginners Calculate savings with Python!

November 26, 2024

UV the game-changer package manager
programming UV the game-changer package manager

November 24, 2024

Beginners Guide for Classes
python Beginners Guide for Classes

November 20, 2024