Strings
Python - A Quick Start for existing Programers
1 min read
This section is 1 min read, full guide is 44 min read
Published Sep 16 2025, updated Sep 30 2025
21
Show sections list
0
Log in to enable the "Like" button
0
Guide comments
0
Log in to enable the "Save" button
Respond to this guide
Guide Sections
Guide Comments
Python
Creating strings
s1 = 'single quotes'
s2 = "double quotes"
s3 = '''triple quotes for multi-line'''
Copy to Clipboard
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
Copy to Clipboard
Toggle show comments
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
Copy to Clipboard
Toggle show comments
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
strftimecodes inside{} - Debugging:
{var=}
Examples:
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old")
print(f"In 5 years, I’ll be {age+5}")
num = 1234.56789
print(f"Default: {num}")
print(f"Two decimals: {num:.2f}")
# 1234.57
print(f"Comma separator: {num:,}")
# 1,234.56789
print(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 = 42
print(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.1415926535
print(f"{pi:.2f}")
# 3.14 (2 decimals)
print(f"{pi:.4f}")
# 3.1416
print(f"{pi:10.2f}")
# Field width 10, 2 decimals -> " 3.14"
num = 1234567.89
print(f"{num:,}")
# 1,234,567.89
print(f"{num:_}")
# 1_234_567.89 (Pythonic underscore style)
num = 255
print(f"{num:b}")
# binary -> 11111111
print(f"{num:o}")
# octal -> 377
print(f"{num:x}")
# hex lowercase -> ff
print(f"{num:X}")
# hex uppercase -> FF
rate = 0.256
print(f"{rate:.0%}")
# 26%
print(f"{rate:.2%}")
# 25.60%
num = 12345.6789
print(f"{num:.2e}")
# 1.23e+04
print(f"{num:.3E}")
# 1.235E+04
from datetime import datetime
now = datetime(2025, 9, 15, 14, 30)
print(f"{now:%Y-%m-%d %H:%M}")
# 2025-09-15 14:30
x = 10
print(f"{x=}")
# x=10
Copy to Clipboard
Toggle show comments
Escape Sequences
print("Line1\nLine2")
# newline
print("Tab\tSpace")
# tab
print("Quote: \"Hello\"")
# escape quotes
print("Backslash: \\")
# backslash
Copy to Clipboard
Toggle show comments
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
Copy to Clipboard
Toggle show comments
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 characters
upper_str = "".join([ch.upper() for ch in text])
print("Uppercase:", upper_str)
# Double each character
doubled = "".join([ch*2 for ch in text])
print("Doubled chars:", doubled)
# ----------------------------------------
# Filtering characters
# ----------------------------------------
# Keep only letters
letters = "".join([ch for ch in text if ch.isalpha()])
print("Letters only:", letters)
# Keep only digits
digits = "".join([ch for ch in text if ch.isdigit()])
print("Digits only:", digits)
# Remove spaces
no_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 uppercase
consonants = "".join([ch.upper() for ch in text if ch.isalpha() and ch.lower() not in "aeiou"])
print("Consonants uppercase:", consonants)
# Reverse string via comprehension
reversed_str = "".join([text[i] for i in range(len(text)-1, -1, -1)])
print("Reversed:", reversed_str)
Copy to Clipboard
Toggle show comments
Raw Strings (ignore escapes)
path = r"C:\Users\Alice\Docs"
print(path)
# C:\Users\Alice\Docs
Copy to Clipboard
Toggle show comments














