Python String Operations
In this page:
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)
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)
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: