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.

--

--

Shen Ge
CodeX

Engineer and console operator who helped America land back on the moon 2/22/2024. Enjoys code + poetry. Become a member: https://medium.com/@shenge86/membership