5.5. String Substitute
5.5.1. Strip Whitespace
str.strip()
- remove whitespaces from both endsstr.lstrip()
- remove whitespaces from left side onlystr.rstrip()
- remove whitespaces from right side onlyWhitespace characters: space (``
), newline (
n``), tab (\t
)
Strip is a very common method, which you should always call upon any text
from user input, that is from input()
function, but also from files,
socket communication and from internet data transfer. You never know, if
the user did not pasted text from other source, which will add whitespace
at the end of at the beginning of a string.
There are three strip methods: left strip, right strip and strip from both ends. Word whitespace refers to:
\n
- newline
\t
- tab`` `` - space
\v
- vertical space
\f
- form-feed
Most common is plain strip, which will remove all whitespace characters from both sides at the same time:
>>> name = ' Alice '
>>>
>>> name.strip()
'Alice'
>>>
>>> name.lstrip()
'Alice '
>>>
>>> name.rstrip()
' Alice'
5.5.2. Strip Characters
str.strip()
- remove whitespaces from both endsstr.lstrip()
- remove whitespaces from left side onlystr.rstrip()
- remove whitespaces from right side only
>>> text = '[INFO]'
>>>
>>> text.strip('[]')
'INFO'
>>>
>>> text.lstrip('[')
'INFO]'
>>>
>>> text.rstrip(']')
'[INFO'
5.5.3. Replace, Removeprefix, Removesuffix
str.replace()
str.removesuffix()
str.removeprefix()
>>> name = 'Alice'
>>>
>>> name.replace('A', 'X')
'Xlice'
>>>
>>> name.replace('a', 'X')
'Alice'
>>>
>>> name.removeprefix('Al')
'ice'
>>>
>>> name.removesuffix('ce')
'Ali'
5.5.4. Use case - 1
>>> filename = '5.05-assignment-a.py'
>>>
>>> filename.removeprefix('5.05-')
'assignment-a.py'
>>>
>>> filename.removesuffix('.py')
'5.05-assignment-a'
>>>
>>> filename.removeprefix('5.05-').removesuffix('.py')
'assignment-a'
5.5.5. Use Case - 2
>>> lvl = '[WARNING]'
>>> lvl.removeprefix('[').removesuffix(']')
'WARNING'
>>> lvl = '[WARNING]'
>>> lvl.replace('[', '').replace(']', '')
'WARNING'
>>> lvl = '[WARNING]'
>>> lvl.strip('[]')
'WARNING'
5.5.6. Use Case - 3
>>> line = '1969-07-21,02:56:15,WARNING,First step on the Moon'
>>>
>>> line.split(',', maxsplit=3)
['1969-07-21', '02:56:15', 'WARNING', 'First step on the Moon']
5.5.7. Use Case - 4
>>> line = '1969-07-21 02:56:15.123 [WARNING] First step on the Moon'
>>> d, t, lvl, msg = line.split(maxsplit=3)
>>> d
'1969-07-21'
>>> t
'02:56:15.123'
>>> lvl.strip('[]')
'WARNING'
>>> msg.title()
'First Step On The Moon'
5.5.8. Use Case - 5
>>> DATA = """1969-07-14, 21:00:00, INFO, Terminal countdown started
... 1969-07-16, 13:31:53, WARNING, S-IC engine ignition (#5)
... 1969-07-16, 13:33:23, DEBUG, Maximum dynamic pressure (735.17 lb/ft^2)
... 1969-07-16, 13:34:44, WARNING, S-II ignition
... 1969-07-16, 13:35:17, DEBUG, Launch escape tower jettisoned
... 1969-07-16, 13:39:40, DEBUG, S-II center engine cutoff
... 1969-07-16, 16:22:13, INFO, Translunar injection
... 1969-07-16, 16:56:03, INFO, CSM docked with LM/S-IVB
... 1969-07-16, 17:21:50, INFO, Lunar orbit insertion ignition
... 1969-07-16, 21:43:36, INFO, Lunar orbit circularization ignition
... 1969-07-20, 17:44:00, INFO, CSM/LM undocked
... 1969-07-20, 20:05:05, WARNING, LM powered descent engine ignition
... 1969-07-20, 20:10:22, ERROR, LM 1202 alarm
... 1969-07-20, 20:14:18, ERROR, LM 1201 alarm
... 1969-07-20, 20:17:39, WARNING, LM lunar landing
... 1969-07-21, 02:39:33, DEBUG, EVA started (hatch open)
... 1969-07-21, 02:56:15, WARNING, 1st step taken lunar surface (CDR)
... 1969-07-21, 02:56:15, WARNING, Neil Armstrong first words on the Moon
... 1969-07-21, 03:05:58, DEBUG, Contingency sample collection started (CDR)
... 1969-07-21, 03:15:16, INFO, LMP on lunar surface
... 1969-07-21, 05:11:13, DEBUG, EVA ended (hatch closed)
... 1969-07-21, 17:54:00, WARNING, LM lunar liftoff ignition (LM APS)
... 1969-07-21, 21:35:00, INFO, CSM/LM docked
... 1969-07-22, 04:55:42, WARNING, Transearth injection ignition (SPS)
... 1969-07-24, 16:21:12, INFO, CM/SM separation
... 1969-07-24, 16:35:05, WARNING, Entry
... 1969-07-24, 16:50:35, WARNING, Splashdown (went to apex-down)
... 1969-07-24, 17:29, INFO, Crew egress"""
>>>
>>> DATA.splitlines()
['1969-07-14, 21:00:00, INFO, Terminal countdown started',
'1969-07-16, 13:31:53, WARNING, S-IC engine ignition (#5)',
'1969-07-16, 13:33:23, DEBUG, Maximum dynamic pressure (735.17 lb/ft^2)',
'1969-07-16, 13:34:44, WARNING, S-II ignition',
'1969-07-16, 13:35:17, DEBUG, Launch escape tower jettisoned',
'1969-07-16, 13:39:40, DEBUG, S-II center engine cutoff',
'1969-07-16, 16:22:13, INFO, Translunar injection',
'1969-07-16, 16:56:03, INFO, CSM docked with LM/S-IVB',
'1969-07-16, 17:21:50, INFO, Lunar orbit insertion ignition',
'1969-07-16, 21:43:36, INFO, Lunar orbit circularization ignition',
'1969-07-20, 17:44:00, INFO, CSM/LM undocked',
'1969-07-20, 20:05:05, WARNING, LM powered descent engine ignition',
'1969-07-20, 20:10:22, ERROR, LM 1202 alarm',
'1969-07-20, 20:14:18, ERROR, LM 1201 alarm',
'1969-07-20, 20:17:39, WARNING, LM lunar landing',
'1969-07-21, 02:39:33, DEBUG, EVA started (hatch open)',
'1969-07-21, 02:56:15, WARNING, 1st step taken lunar surface (CDR)',
'1969-07-21, 02:56:15, WARNING, Neil Armstrong first words on the Moon',
'1969-07-21, 03:05:58, DEBUG, Contingency sample collection started (CDR)',
'1969-07-21, 03:15:16, INFO, LMP on lunar surface',
'1969-07-21, 05:11:13, DEBUG, EVA ended (hatch closed)',
'1969-07-21, 17:54:00, WARNING, LM lunar liftoff ignition (LM APS)',
'1969-07-21, 21:35:00, INFO, CSM/LM docked',
'1969-07-22, 04:55:42, WARNING, Transearth injection ignition (SPS)',
'1969-07-24, 16:21:12, INFO, CM/SM separation',
'1969-07-24, 16:35:05, WARNING, Entry',
'1969-07-24, 16:50:35, WARNING, Splashdown (went to apex-down)',
'1969-07-24, 17:29, INFO, Crew egress']
5.5.9. Assignments
# %% About
# - Name: Type Str Strip
# - 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. Define variable `result_a` with `DATA` stripped on both sides
# 2. Define variable `result_b` with `DATA` stripped on left side only
# 3. Define variable `result_c` with `DATA` stripped on right side only
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj zmienną `result_a` z `DATA` usuniętymi whitespace po obu stronach
# 2. Zdefiniuj zmienną `result_b` z `DATA` obciętym tylko z lewej strony
# 3. Zdefiniuj zmienną `result_c` z `DATA` obciętym tylko z prawej strony
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result_a
# 'Hello World'
# >>> result_b
# 'Hello World\n'
# >>> result_c
# '\t Hello World'
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result_a is not Ellipsis, \
'Assign your result to variable `result_a`'
>>> assert type(result_a) is str, \
'Variable `result_a` has invalid type, should be str'
>>> result_a
'Hello World'
>>> assert result_b is not Ellipsis, \
'Assign your result to variable `result_b`'
>>> assert type(result_b) is str, \
'Variable `result_b` has invalid type, should be str'
>>> result_b
'Hello World\\n'
>>> assert result_c is not Ellipsis, \
'Assign your result to variable `result_c`'
>>> assert type(result_c) is str, \
'Variable `result_c` has invalid type, should be str'
>>> result_c
'\\t Hello World'
"""
# %% 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_a: str
result_b: str
result_c: str
# %% Data
DATA = '\t Hello World\n'
# %% Result
result_a = ...
result_b = ...
result_c = ...
# %% About
# - Name: Type Str Remove Prefix and Suffix
# - 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. Define variable `result_a` with `DATA` without character `[` at the beginning
# 2. Define variable `result_b` with `DATA` without character `]` at the end
# 3. Define variable `result_c` with `DATA` without characters `[` and `]`
# 4. Use `str.removeprefix()` i `str.removesuffix()`
# 5. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj zmienną `result_a` z `DATA` bez znaku `[` na początku
# 2. Zdefiniuj zmienną `result_b` z `DATA` bez znaku `]` na końcu
# 3. Zdefiniuj zmienną `result_c` z `DATA` bez znaków `[` i `]`
# 4. Użyj `str.removeprefix()` i `str.removesuffix()`
# 5. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result_a
# 'INFO]'
# >>> result_b
# '[INFO'
# >>> result_c
# 'INFO'
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result_a is not Ellipsis, \
'Assign your result to variable `result_a`'
>>> assert type(result_a) is str, \
'Variable `result_a` has invalid type, should be str'
>>> result_a
'INFO]'
>>> assert result_b is not Ellipsis, \
'Assign your result to variable `result_b`'
>>> assert type(result_b) is str, \
'Variable `result_b` has invalid type, should be str'
>>> result_b
'[INFO'
>>> assert result_c is not Ellipsis, \
'Assign your result to variable `result_c`'
>>> assert type(result_c) is str, \
'Variable `result_c` has invalid type, should be str'
>>> result_c
'INFO'
"""
# %% 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_a: str
result_b: str
result_c: str
# %% Data
DATA = '[INFO]'
# %% Result
result_a = ...
result_b = ...
result_c = ...
# %% About
# - Name: Type Str Remove Prefix and Suffix
# - 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. Define variable `result_a` with `DATA` without character `[` at the beginning
# 2. Define variable `result_b` with `DATA` without character `]` at the end
# 3. Define variable `result_c` with `DATA` without characters `[` and `]`
# 4. Use `str.strip()`, `str.lstrip()`, `str.rstrip()`
# 5. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj zmienną `result_a` z `DATA` bez znaku `[` na początku
# 2. Zdefiniuj zmienną `result_b` z `DATA` bez znaku `]` na końcu
# 3. Zdefiniuj zmienną `result_c` z `DATA` bez znaków `[` i `]`
# 4. Use `str.strip()`, `str.lstrip()`, `str.rstrip()`
# 5. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result_a
# 'INFO]'
# >>> result_b
# '[INFO'
# >>> result_c
# 'INFO'
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result_a is not Ellipsis, \
'Assign your result to variable `result_a`'
>>> assert type(result_a) is str, \
'Variable `result_a` has invalid type, should be str'
>>> result_a
'INFO]'
>>> assert result_b is not Ellipsis, \
'Assign your result to variable `result_b`'
>>> assert type(result_b) is str, \
'Variable `result_b` has invalid type, should be str'
>>> result_b
'[INFO'
>>> assert result_c is not Ellipsis, \
'Assign your result to variable `result_c`'
>>> assert type(result_c) is str, \
'Variable `result_c` has invalid type, should be str'
>>> result_c
'INFO'
"""
# %% 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_a: str
result_b: str
result_c: str
# %% Data
DATA = '[INFO]'
# %% Result
result_a = ...
result_b = ...
result_c = ...