How do I work with strings and common string methods in Python?
· Category: Python Programming
Short answer
Python strings are immutable sequences of characters. You can slice them, concatenate them, and use dozens of built-in methods for transformation, searching, and validation.
Steps
- Create strings with quotes or triple quotes.
- Access characters by index and slice with
[start:stop:step]. - Use methods like
.lower(),.strip(),.replace(),.split(), and.join().
text = " Hello, World! "
print(text.strip()) # "Hello, World!"
print(text.lower()) # " hello, world! "
print(text.replace("World", "Python")) # " Hello, Python! "
print("apple,banana".split(",")) # ['apple', 'banana']
print("-".join(["a", "b", "c"])) # a-b-c
# Slicing
s = "Python"
print(s[0:2]) # Py
print(s[::-1]) # nohtyP
Tips
- Strings are immutable, so methods return new strings rather than modifying the original.
- Use
.startswith()and.endswith()for clean prefix/suffix checks. .find()returns-1if the substring is not found;.index()raisesValueError.- Raw strings (
r"path") are useful for regular expressions and Windows paths.
Common issues
- Trying to modify a string in place (e.g.,
s[0] = 'J') raises aTypeError. - Concatenating strings in a loop with
+is slow; usestr.join()or a list buffer instead. - Unicode and byte strings are different types in Python 3; decode bytes before treating them as text.