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

  1. Create strings with quotes or triple quotes.
  2. Access characters by index and slice with [start:stop:step].
  3. 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 -1 if the substring is not found; .index() raises ValueError.
  • 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 a TypeError.
  • Concatenating strings in a loop with + is slow; use str.join() or a list buffer instead.
  • Unicode and byte strings are different types in Python 3; decode bytes before treating them as text.