Andromeda
Note

Strings (Python)

Definition

A fundamental data type representing a series of characters, typically used for text. In Python, they are defined using single (') or double (") quotes.

Why It Matters

Strings are the primary medium of human-computer interaction; their immutability in Python ensures referential integrity and thread-safety, making them the most reliable tool for encoding, cleaning, and communicating symbolic information across a system.

Core Concepts

  • String Literals:
    • Single (') and Double (") quotes are interchangeable.
    • Escape Characters: Use \ to include forbidden characters: \', \", \t, \n, \\.
    • Raw Strings: Preceded by r (e.g., r'C:\Users'), they ignore escape characters.
    • Multiline Strings: Triple quotes (''' or """) allow strings to span multiple lines.
  • String Methods:
    • Case Conversion: upper(), lower(), title(), isupper(), islower().
    • Validation: isalpha(), isalnum(), isdecimal(), isspace(), istitle().
    • Join/Split: ' '.join(list) (joins a list into a string) and 'string'.split() (splits a string into a list).
    • Alignment: rjust(), ljust(), and center() for adding padding characters.
    • Whitespace: strip(), rstrip(), lstrip().
  • F-Strings (Interpolation): Modern standard for inserting variables: f"Hello {name}".
  • Immutability: String methods return new strings; they do not change the original object in memory.
name = "ada lovelace"
message = f"Hello, {name.title()}!"
print(message) # Output: Hello, Ada Lovelace!

clean_text = "  spaced out  ".strip()
print(f"'{clean_text}'") # Output: 'spaced out'

Connected Concepts