5.6. String Convert

5.6.1. Split by Character

  • str.split() - Split by given character

  • str.split(sep, maxsplit=3) - split by max number of splits

  • No argument - any number of whitespaces

>>> data = 'Alice,Bob,Carol'
>>>
>>> data.split(',')
['Alice', 'Bob', 'Carol']

5.6.2. Split by Space

  • str.split() - Split by given character

  • str.split(sep, maxsplit=3) - split by max number of splits

  • Whitespace characters: space (`` ), newline (n``), tab (\t)

>>> data = 'Alice Bob Carol'
>>>
>>> data.split()
['Alice', 'Bob', 'Carol']
>>>
>>> data.split(' ')
['Alice', 'Bob', 'Carol']

Example with separator:

>>> data = 'Alice    Bob    Carol'
>>>
>>> data.split()
['Alice', 'Bob', 'Carol']
>>>
>>> data.split(' ')
['Alice', '', '', '', 'Bob', '', '', '', 'Carol']

Example with maxsplit:

>>> data = '2000-01-01 00:00:00 ERROR Unexpected behavior happened'
>>>
>>> data.split()
['2000-01-01', '00:00:00', 'ERROR', 'Unexpected', 'behavior', 'happened']
>>>
>>> data.split(maxsplit=3)
['2000-01-01', '00:00:00', 'ERROR', 'Unexpected behavior happened']

5.6.3. Split by Line

  • str.splitlines() - split by newline character, don't leave empty lines at the end

  • str.split('\n') - will leave empty string if newline is a the end of str

>>> text = 'Alice\nBob\nCarol'
>>>
>>> text.splitlines()
['Alice', 'Bob', 'Carol']
>>>
>>> text.split('\n')
['Alice', 'Bob', 'Carol']

Longer text:

>>> text = """Lorem ipsum dolor sit amet, consectetur adipiscing elit,
... sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
... Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
... nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
... reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
... pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
... culpa qui officia deserunt mollit anim id est laborum."""
>>>
>>>
>>> text.splitlines()
['Lorem ipsum dolor sit amet, consectetur adipiscing elit,',
 'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris',
 'nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in',
 'reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla',
 'pariatur. Excepteur sint occaecat cupidatat non proident, sunt in',
 'culpa qui officia deserunt mollit anim id est laborum.']

5.6.4. Join by Character

  • [1]

  • str.join(sep, sequence) - concatenate sequence using separator

  • Note, this is a method of a str, not tuple.join() or list.join()

>>> names = ['Alice', 'Bob', 'Carol']
>>>
>>> ','.join(names)
'Alice,Bob,Carol'
>>>
>>> ';'.join(names)
'Alice;Bob;Carol'
>>>
>>> ' '.join(names)
'Alice Bob Carol'
>>>
>>> '\n'.join(names)
'Alice\nBob\nCarol'

5.6.5. Use Case - 1

>>> data = 'Alice,Apricot,alice@example.com\n'
>>>
>>> data.split(',')
['Alice', 'Apricot', 'alice@example.com\n']
>>>
>>> data.strip().split(',')
['Alice', 'Apricot', 'alice@example.com']

5.6.6. Use Case - 2

>>> data = ['Alice', 'Apricot', 'alice@example.com']
>>>
>>> ','.join(data)
'Alice,Apricot,alice@example.com'
>>>
>>> ','.join(data) + '\n'
'Alice,Apricot,alice@example.com\n'

5.6.7. References

5.6.8. Assignments

# %% About
# - Name: Type Str Split
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Split `DATA` by lines
# 2. Run doctests - all must succeed

# %% Polish
# 1. Podziel `DATA` po liniach
# 2. Uruchom doctesty - wszystkie muszą się powieść

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'

>>> assert len(result) == 3, \
'Variable `result` length should be 3'

>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> line = 'Alice'
>>> assert line in result, f'Line "{line}" is not in the result'

>>> line = 'Bob'
>>> assert line in result, f'Line "{line}" is not in the result'

>>> line = 'Carol'
>>> assert line in result, f'Line "{line}" is not in the result'
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
result: list[str]

# %% Data
DATA = 'Alice,Bob,Carol'

# %% Result
result = ...

# %% About
# - Name: Type Str Split
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Split `DATA` by lines
# 2. Run doctests - all must succeed

# %% Polish
# 1. Podziel `DATA` po liniach
# 2. Uruchom doctesty - wszystkie muszą się powieść

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'

>>> assert len(result) == 3, \
'Variable `result` length should be 3'

>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> line = 'Alice'
>>> assert line in result, f'Line "{line}" is not in the result'

>>> line = 'Bob'
>>> assert line in result, f'Line "{line}" is not in the result'

>>> line = 'Carol'
>>> assert line in result, f'Line "{line}" is not in the result'
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
result: list[str]

# %% Data
DATA = 'Alice Bob Carol'

# %% Result
result = ...

# %% About
# - Name: Type Str Splitlines
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Split `DATA` by lines
# 2. Run doctests - all must succeed

# %% Polish
# 1. Podziel `DATA` po liniach
# 2. Uruchom doctesty - wszystkie muszą się powieść

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'

>>> assert len(result) == 3, \
'Variable `result` length should be 3'

>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> line = 'Alice'
>>> assert line in result, f'Line "{line}" is not in the result'

>>> line = 'Bob'
>>> assert line in result, f'Line "{line}" is not in the result'

>>> line = 'Carol'
>>> assert line in result, f'Line "{line}" is not in the result'
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
result: list[str]

# %% Data
DATA = 'Alice\nBob\nCarol'

# %% Result
result = ...

# %% About
# - Name: Type Str Splitlines
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Split `DATA` by lines
# 2. Run doctests - all must succeed

# %% Polish
# 1. Podziel `DATA` po liniach
# 2. Uruchom doctesty - wszystkie muszą się powieść

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'

>>> assert len(result) == 4, \
'Variable `result` length should be 4'

>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> line = 'First line'
>>> assert line in result, f'Line "{line}" is not in the result'

>>> line = 'Second line'
>>> assert line in result, f'Line "{line}" is not in the result'

>>> line = 'Third line'
>>> assert line in result, f'Line "{line}" is not in the result'

>>> line = 'Fourth line'
>>> assert line in result, f'Line "{line}" is not in the result'
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
result: list[str]

# %% Data
DATA = """First line
Second line
Third line
Fourth line"""

# %% Result
result = ...