10 Python One-Liners for Strings

Shen Ge
CodeX
Published in
6 min readJul 4, 2022

--

Photo by Aditya Wardhana on Unsplash

Background on Strings

Functionally, strings can represent just about anything that can be encoded as text or bytes. Python’s strings serve the same role as character arrays in languages such as C but they are a higher-level tool than arrays. They are classified as immutable sequences, meaning characters within have a left-to-right positional order and that they cannot be changed in place. Note that even though a string cannot be changed in place, you can still modify text information by building and assigning a new string before then assigning the result back to the string’s original name.

Empty strings are written as a pair of quotation marks (single or double) with nothing in between. Strings support expression operations such as concatenation, slicing, indexing , etc. Python also provides string methods which implement string-specific tasks as well as modules for more advanced processing such as pattern matching.

1. Concatenating strings

Use the + operator and repeat them using the * operator. Formerly, adding string objects creates a new string object whereas repetition is like adding a string to itself multiple times. Note that Python lets you create arbitrarily sized strings with no need to predeclare anything including the size of data structures.

>>> 'abc' + 'def'
'abcdef'
>>> 'Hi!' * 4
'HiHiHiHi'
>>> print('-'*80) # 80 dashes, the easy way
--------------------------------------------------------------------------------

2. Test membership in a string

You can test membership for both characters and substrings with the in expression operator, which is a search within the string.

There are also string methods with more focused roles, for example endswith and startswith

>>> myjob = 'pythoner'
>>> 'python' in myjob # Substring search; no position returned
True
>>> 'p' in myjob # Found
True
>>> 'q' in myjob # Not found
False
>>> myjob.startswith('py')
True
>>> myjob.endswith('er')
False

3. Indexing and slicing

Because strings are defined as ordered collections of characters, we can access components by position. In Python, characters in a string…

--

--

Shen Ge
CodeX
Writer for

Aerospace engineer who enjoys Python, math, physics, space and poetry. Become a member and read all my work: https://medium.com/@shenge86/membership