Tutorials Logic, IN info@tutorialslogic.com

Python String Methods split, join, replace, format

Python Strings

A Python string stores text as an ordered sequence of characters. You can read characters by index, slice parts of the text, and create new strings with methods.

Strings are immutable, so methods such as strip(), replace(), lower(), and title() return a new string instead of changing the old one in place.

Most string bugs come from assuming a separator, index, or length exists. Check the input shape before slicing, splitting, or converting text.

Python String

A string is a sequence of characters enclosed in single, double, or triple quotes. Strings are immutable - once created, they cannot be changed in place.

Create Strings

Quotes, Escapes, and Raw Text

Quotes, Escapes, and Raw Text
single = 'single quotes'
double = "double quotes"
multiline = """A string can span
multiple lines."""

tab = "Hello\tWorld"
newline = "Line 1\nLine 2"
quote = "She said \"hi\""
backslash = "C:\\Users\\Alice"

path = r"C:\Users\Alice\Documents"
pattern = r"\d+\.\d+"

print(len("Python"))
print(type("hello"))

Indexing and Slicing

Indexing & Slicing

Indexing & Slicing
s = "Python"
#    P y t h o n
#    0 1 2 3 4 5   (positive index)
#   -6-5-4-3-2-1   (negative index)

print(s[0])     # P
print(s[-1])    # n
print(s[2])     # t

# Slicing: s[start:stop:step]
print(s[1:4])   # yth
print(s[:3])    # Pyt
print(s[3:])    # hon
print(s[::2])   # Pto  (every 2nd char)
print(s[::-1])  # nohtyP  (reversed)

# Strings are immutable
# s[0] = "J"  # TypeError!
# Create a new string instead:
new_s = "J" + s[1:]
print(new_s)    # Jython

Format Strings

Format Names, Numbers, and Reports

Format Names, Numbers, and Reports
name = "Alice"
age = 25
pi = 3.14159

# f-strings (Python 3.6+) - recommended
print(f"Hello, {name}! You are {age} years old.")
print(f"Pi = {pi:.2f}")          # 2 decimal places
print(f"{age:05d}")               # 00025 (zero-padded)
print(f"{'left':<10}|")          # left-aligned
print(f"{'right':>10}|")         # right-aligned
print(f"{'center':^10}|")        # centered
print(f"{1_000_000:,}")          # 1,000,000 (thousands separator)

# format() method
print("Hello, {}! Age: {}".format(name, age))
print("Hello, {name}!".format(name="Bob"))

# % formatting (old style)
print("Hello, %s! Age: %d" % (name, age))
print("Pi = %.2f" % pi)

# Multiline f-string
report = (
    f"Name: {name}\n"
    f"Age:  {age}\n"
    f"Pi:   {pi:.4f}"
)
print(report)

String Methods

Method Description Example
upper() Uppercase "hi".upper() -> "HI"
lower() Lowercase "HI".lower() -> "hi"
title() Title case "hello world".title() -> "Hello World"
strip() Remove leading/trailing whitespace " hi ".strip() -> "hi"
lstrip() / rstrip() Strip left or right only
replace(old, new) Replace substring "abc".replace("b","x") -> "axc"
split(sep) Split into list "a,b,c".split(",") -> ['a','b','c']
join(iterable) Join list into string ",".join(["a","b"]) -> "a,b"
find(sub) Index of first occurrence (-1 if not found) "hello".find("l") -> 2
index(sub) Like find but raises ValueError
count(sub) Count occurrences "hello".count("l") -> 2
startswith(s) Check prefix "hello".startswith("he") -> True
endswith(s) Check suffix "hello".endswith("lo") -> True
isdigit() All digits- "123".isdigit() -> True
isalpha() All letters- "abc".isalpha() -> True
isalnum() Letters or digits-
zfill(n) Zero-pad to width n "42".zfill(5) -> "00042"
center(n) Center in width n "hi".center(10)

Methods in Action

Methods in Action
text = "  Hello, World!  "

print(text.strip())           # "Hello, World!"
print(text.lower())           # "  hello, world!  "
print(text.upper())           # "  HELLO, WORLD!  "
print(text.replace("World", "Python"))  # "  Hello, Python!  "

csv = "apple,banana,cherry"
fruits = csv.split(",")
print(fruits)                 # ['apple', 'banana', 'cherry']
print(" | ".join(fruits))     # apple | banana | cherry

sentence = "the quick brown fox"
print(sentence.title())       # The Quick Brown Fox
print(sentence.count("the"))  # 1
print(sentence.find("quick")) # 4
print(sentence.startswith("the"))  # True

# Method chaining
clean = "  HELLO WORLD  ".strip().lower().replace(" ", "_")
print(clean)   # hello_world

String Operations

Operations

Operations
first = "Hello"
last = "World"
print(first + ", " + last + "!")
print("ha" * 3)
print("ell" in "Hello")

chars = list("Python")
print(chars)

template = """Dear {name},

Your order #{order_id} has shipped.
Expected delivery: {date}
"""
print(template.format(name="Alice", order_id=12345, date="June 20"))

Text Cleanup

Real text often contains extra spaces, missing separators, unexpected casing, or empty values. Clean the text first, then split or convert it.

When split() is used for structured input, check how many parts came back. If the separator may be missing, partition() can be safer because it always returns three values.

When slicing, remember that a missing index can still return an empty string rather than an error. Print repr(value) while debugging so spaces and blank strings are visible.

  • Use strip() before comparing user-entered text.
  • Assign the result of replace(), lower(), upper(), or title().
  • Check len(parts) after split() when input may be incomplete.
  • Use repr(text) to reveal hidden spaces and newline characters.
String readiness check

Can You Clean and Transform Text Safely?

5 checks
  • Use indexing and slicing for positions inside text.
  • Use strip(), replace(), split(), and join() for common cleanup tasks.
  • Use f-strings for readable formatting.
  • Remember strings are immutable; methods return new strings.
  • Validate text before converting it to numbers or dates.

String Decisions

0 of 2 checked

Q1. What does text.strip() do?

Q2. Which style is clearest for inserting a variable into text?

Text Bugs to Catch

  • Forgetting strings are immutable

    Create a new string from replace, strip, lower, or slicing instead of expecting the old one to change.
  • Comparing unclean text

    Normalize user text with strip() and lower() before comparing choices.
  • Building long text with many plus signs

    Use f-strings for readable values inside text.

Try this next

Clean User Text

0 of 3 completed

  1. Convert user input like " Yes " into yes before checking it.
  2. Use an f-string to print item name, quantity, and total.
  3. Extract a prefix and suffix from an order ID string.

String Choices

Strings are immutable. Methods such as replace and strip return a new string, so assign the result if you need to keep it.

It returns a one-item list containing the original string. Code expecting two parts should check the length or use partition.

Use find when a missing substring is expected and -1 is convenient. index raises ValueError when no match exists.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.