Difficulty: Beginner
Python strings support several operators that make working with text intuitive. The + operator concatenates (joins) two strings together, creating a new string. The * operator repeats a string a given number of times. These are the two fundamental string operators.
The in and not in operators test whether a substring exists within a string, returning True or False. These membership operators are case-sensitive: "python" in "Python is great" returns False because the cases don't match. For case-insensitive checks, convert both strings to the same case first.
Strings can be compared using comparison operators (==, !=, <, >, <=, >=). String comparison is lexicographic, meaning Python compares characters one by one using their Unicode code point values. Uppercase letters have lower code points than lowercase letters, so "Apple" < "banana" is True (because 'A' has code point 65 while 'b' has code point 98).
A fundamental property of Python strings is immutability. Once a string is created, you cannot change any individual character. Operations like concatenation, replace(), and upper() always produce new string objects. Attempting text[0] = "X" raises a TypeError. If you need to build a string incrementally, use a list of parts and join them at the end for better performance.
greeting = "Hello" + " " + "World"
line = "-" * 20
border = "*" * 3 + " Title " + "*" * 3
print(greeting)
print(line)
print(border)
The + operator joins strings. The * operator repeats a string. Both create new strings; neither modifies the originals.
text = "Python programming is powerful"
print("Python" in text)
print("python" in text)
print("Java" not in text)
print("python" in text.lower())
The in operator is case-sensitive. 'python' is not found because the original has 'Python'. Converting to lower() makes the check case-insensitive.
print("apple" == "apple")
print("apple" < "banana")
print("Apple" < "apple")
print("abc" < "abd")
print(ord("A"), ord("a"))
Strings are compared character by character using Unicode code points. 'A' (65) < 'a' (97), so uppercase letters sort before lowercase.
text = "Hello"
# Cannot do: text[0] = "J" -> TypeError
# Instead, create a new string:
new_text = "J" + text[1:]
print(new_text)
print(text)
print(id(text) != id(new_text))
The original string 'Hello' is unchanged. A new string 'Jello' is created by concatenating 'J' with a slice. id() confirms they are different objects.
concatenation, repetition, membership, comparison, immutability