Strings

Python - A Quick Start for existing Programers

1 min read

Published Sep 16 2025, updated Aug 17 2026


21
0
0
0

Python

Creating strings

s1 = 'single quotes's2 = "double quotes"s3 = '''triple quotes for multi-line'''



Basic string operations

s = "Hello World"​print(len(s))        # length​print(s[0])          # indexing (H)​print(s[-1])         # last character (d)​print(s[0:5])        # slicing ("Hello")​print("Hello" in s)  # membership (True)​print(s + "!")       # concatenation​print(s * 3)         # repetition



Common string methods

txt = "  Python is Fun!  "​print(txt.lower())       # "  python is fun!  "​print(txt.upper())       # "  PYTHON IS FUN!  "​print(txt.title())       # "  Python Is Fun!  "​print(txt.strip())       # "Python is Fun!" (remove spaces)​print(txt.replace("Fun", "Awesome"))  # "  Python is Awesome!  "​print(txt.split())       # ['Python', 'is', 'Fun!']​print(",".join(["a","b","c"]))  # "a,b,c"​print(txt.find("Fun"))   # index of substring​print(txt.startswith("Py"))  # False​print(txt.endswith("!"))     # True



f-strings

Adding an f before a string allows you to add variables in the string which are resolved and can be formatted

  • Width & alignment: <, >, ^, = (padding before sign)
  • Fill character: {value:*^10}
  • Signs: +, -, (space for positives)
  • Numbers: .nf (decimals), , (comma), _ (underscore), b (binary), o (octal), x/X (hex), e/E (scientific), % (percentage)
  • Datetime: use strftime codes inside {}
  • Debugging: {var=}


Examples:

name = "Alice"age = 30print(f"My name is {name} and I am {age} years old")print(f"In 5 years, I’ll be {age+5}")​num = 1234.56789print(f"Default: {num}")print(f"Two decimals: {num:.2f}")       # 1234.57print(f"Comma separator: {num:,}")      # 1,234.56789print(f"Percent: {0.25:.0%}")           # 25%print(f"Scientific: {num:.2e}")         # 1.23e+03​text = "Hi"print(f"[{text:<10}]")   # Left-align within 10 spaces -> [Hi        ]print(f"[{text:>10}]")   # Right-align within 10 spaces -> [        Hi]print(f"[{text:^10}]")   # Center -> [    Hi    ]print(f"[{text:*^10}]")  # Center, fill with * -> [****Hi****]​num = 42print(f"[{num:5}]")      # Width 5 -> [   42]print(f"[{num:05}]")     # Zero-padding -> [00042]print(f"[{num:+}]")      # Always show sign -> [+42]print(f"[{-num:+}]")     # [-42]print(f"[{num: }]", f"[{-num: }]")  # Space for positive -> [ 42] [-42]​pi = 3.1415926535print(f"{pi:.2f}")    # 3.14 (2 decimals)print(f"{pi:.4f}")    # 3.1416print(f"{pi:10.2f}")  # Field width 10, 2 decimals -> "      3.14"​num = 1234567.89print(f"{num:,}")      # 1,234,567.89print(f"{num:_}")      # 1_234_567.89 (Pythonic underscore style)​num = 255print(f"{num:b}")   # binary -> 11111111print(f"{num:o}")   # octal -> 377print(f"{num:x}")   # hex lowercase -> ffprint(f"{num:X}")   # hex uppercase -> FF​rate = 0.256print(f"{rate:.0%}")   # 26%print(f"{rate:.2%}")   # 25.60%​num = 12345.6789print(f"{num:.2e}")   # 1.23e+04print(f"{num:.3E}")   # 1.235E+04​from datetime import datetimenow = datetime(2025, 9, 15, 14, 30)print(f"{now:%Y-%m-%d %H:%M}")   # 2025-09-15 14:30​x = 10print(f"{x=}")   # x=10



Escape Sequences

print("Line1\nLine2")   # newline​print("Tab\tSpace")     # tab​print("Quote: \"Hello\"") # escape quotes​print("Backslash: \\")  # backslash



String checking methods

s = "Python3"​print(s.isalpha())   # False (contains digit)​print(s.isdigit())   # False​print(s.isalnum())   # True (letters + digits)​print(s.isspace())   # False​print("HELLO".isupper())  # True​print("hello".islower())  # True



String comprehensions

  • Python can use list comprehensions on strings.
  • Use "".join(...) to rebuild a string after transformation/filtering.
  • You can do:
    • Transformations (uppercase, doubling)
    • Filtering (keep only certain chars)
    • Conditional replacements (mask vowels/digits)

Examples:

text = "Python 3.12!"​# ----------------------------------------# Basic transformations# ----------------------------------------# Uppercase all charactersupper_str = "".join([ch.upper() for ch in text])print("Uppercase:", upper_str)​# Double each characterdoubled = "".join([ch*2 for ch in text])print("Doubled chars:", doubled)​# ----------------------------------------# Filtering characters# ----------------------------------------# Keep only lettersletters = "".join([ch for ch in text if ch.isalpha()])print("Letters only:", letters)​# Keep only digitsdigits = "".join([ch for ch in text if ch.isdigit()])print("Digits only:", digits)​# Remove spacesno_spaces = "".join([ch for ch in text if ch != " "])print("No spaces:", no_spaces)​# ----------------------------------------# Conditional replacements# ----------------------------------------# Replace vowels with '*'mask_vowels = "".join(["*" if ch.lower() in "aeiou" else ch for ch in text])print("Mask vowels:", mask_vowels)​# Replace digits with '#'mask_digits = "".join(["#" if ch.isdigit() else ch for ch in text])print("Mask digits:", mask_digits)​# ----------------------------------------# Combining rules# ----------------------------------------# Only consonants, all uppercaseconsonants = "".join([ch.upper() for ch in text if ch.isalpha() and ch.lower() not in "aeiou"])print("Consonants uppercase:", consonants)​# Reverse string via comprehensionreversed_str = "".join([text[i] for i in range(len(text)-1, -1, -1)])print("Reversed:", reversed_str)




Raw Strings (ignore escapes)

path = r"C:\Users\Alice\Docs"print(path)  # C:\Users\Alice\Docs
© 2025 SimpleSteps.guide
AboutFAQPoliciesContact