Python String Operations
In this page:
string1 + string2
string * n
substring in string
len(string)
String Concatenation
The + operator joins strings end to end into a new string; because strings are immutable in Python, concatenating in a loop repeatedly creates new objects, which is why joining many pieces with ''.join(list) is the more efficient idiom for large amounts of text.
Example: String Concatenation
first = "Hello"
second = "World"
print(first + " " + second) # + joins the strings end to end into a new string
String Repetition
Multiplying a string by an integer with * repeats it that many times, which is a quick way to build separators, padding, or ASCII-art borders like '-' * 40 without writing a loop.
Example: String Repetition
print("-" * 10)
Membership Operators
in and 'not in' check for substring presence and return a boolean, making them the simplest way to test membership before doing more expensive parsing -- for example checking if '@' in email before attempting to validate an address further.
Example: Membership Operators
email = "[email protected]"
print("@" in email)
Comparing Strings
Comparison operators like < and > compare strings character by character using Unicode code points, so Apple < apple is True because uppercase letters sort before lowercase ones -- a frequent source of bugs when sorting user input without normalizing case first.
Example: Comparing Strings
print("Apple" < "apple")
Iterating over Strings
Looping over a string with a for loop visits one character at a time in order, which is useful for tasks like counting vowels or building a character-frequency map without needing index-based access via range(len(s)).
Example: Iterating over Strings
for char in "cat":
print(char)
- Concatenating a string and a number with
+, as in"Age: " + 25, which raisesTypeError; usestr(25)or an f-string. - Building a large string with
+=in a long loop instead of"".join(parts), which is slower because each step creates a new string. - Comparing strings with different case, as in
"apple" == "Apple", which isFalse; normalise with.lower()first.
- Strings have many methods and support slicing and formatting.
- Regular expressions match patterns in text.
- String operations combine and manipulate text.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: