Working with Strings

String methods and formatting

What Is a String?

A string is an immutable sequence of characters used to represent text in Python. Strings are enclosed in single quotes ‘…’, double quotes “…”, or triple quotes ”’…”’/”””…””” for multi-line strings.

greeting = “Hello, world!”

Common String Methods

String methods are built-in functions you can use to manipulate or inspect strings. They do not change the original string but return a new one.

lower() / upper()

Converts all characters to lowercase or uppercase.

“Python”.lower() # ‘python’
“code”.upper() # ‘CODE’

capitalize() / title()

Capitalizes the first character or the first letter of each word.

“hello world”.capitalize() # ‘Hello world’
“python is fun”.title() # ‘Python Is Fun’

strip(), lstrip(), rstrip()

Removes whitespace or specified characters from both/single sides.

” hello “.strip() # ‘hello’
“—text—“.strip(‘-‘) # ‘text’

replace(old, new)

Replaces part of the string with something else.

“cats are cool”.replace(“cats”, “dogs”) # ‘dogs are cool’

split(separator) / join(iterable)

  • split() turns a string into a list.
  • join() turns a list into a string.

“one,two,three”.split(‘,’) # [‘one’, ‘two’, ‘three’]
“,”.join([“a”, “b”, “c”]) # ‘a,b,c’

find() / index()

Returns the position of the first occurrence of a substring. find() returns -1 if not found, while index() raises an error.

“hello”.find(“e”) # 1
“hello”.index(“e”) # 1

startswith() / endswith()

Checks if a string starts or ends with a given substring.

“url.com”.startswith(“http”) # False
“url.com”.endswith(“.com”) # True

count(substring)

Counts how many times a substring occurs.

“banana”.count(“a”) # 3

isalpha(), isdigit(), isalnum(), isspace()

Check string properties:

“abc”.isalpha() # True
“123”.isdigit() # True
“abc123”.isalnum() # True
” “.isspace() # True

String Formatting in Python

Python offers multiple ways to insert variables into strings.

1. f-Strings (Python 3.6+) – Best and cleanest

name = “Alice”
age = 30
print(f”My name is {name} and I’m {age} years old.”)

2. .format() Method

“Hello, {}. You are {}.”.format(“Bob”, 25)

With named placeholders:

“Hello, {name}. You are {age}.”.format(name=”Bob”, age=25)

3. Percent (%) Formatting – Older style

“%s is %d years old.” % (“Tom”, 40)

Advanced f-String Features

You can even evaluate expressions inside f-strings:

price = 19.99
print(f”Total after tax: ${price * 1.07:.2f}”) # Format to 2 decimal places

Summary:

  • Strings are immutable sequences of characters.
  • Use methods like lower(), replace(), split(), find(), and strip() to manipulate text.
  • Use f-strings, .format(), or % for inserting variables or expressions into strings.

f-strings

What Are f-Strings?

f-strings are a string formatting method introduced in Python 3.6 that allow you to embed expressions directly inside string literals using {} brackets, prefixed by an f or F.

name = “Alice”
print(f”Hello, {name}!”) # Output: Hello, Alice!

Syntax

f”some text {expression} more text”

  • Place expressions inside {}.
  • Variables, calculations, and even function calls are allowed inside the brackets.
  • Add an f before the string — single, double, or triple quotes.

Basic Examples

name = “Bob”
age = 30
print(f”{name} is {age} years old.”)
# Output: Bob is 30 years old.

Expressions Inside f-Strings

You can evaluate any valid expression inside {}:

a = 5
b = 3
print(f”{a} + {b} = {a + b}”)
# Output: 5 + 3 = 8

You can also call functions:

def greet(name):
return f”Hello, {name}!”

print(f”{greet(‘Alice’)}, welcome!”)
# Output: Hello, Alice!, welcome!

Formatting Numbers

Decimal Precision:

pi = 3.14159
print(f”Value of pi: {pi:.2f}”) # Output: Value of pi: 3.14

Thousand Separators:

big_number = 1000000
print(f”{big_number:,}”) # Output: 1,000,000

Formatting Dates

You can format datetime objects too:

from datetime import datetime
now = datetime.now()
print(f”Date: {now:%Y-%m-%d}, Time: {now:%H:%M}”)

Debugging with f-Strings (Python 3.8+)

Using the = sign shows both the variable and its value:

f-Strings vs Other Methods

Method Readability Performance Flexibility
f-string Best Fastest High
.format() Okay Slower High
% Outdated Slower Low

What f-Strings Can’t Do

  • Only available in Python 3.6+
  • Can’t use backslashes (\) in the expression inside {}

Summary:

  • f-strings make formatting clean, readable, and efficient.
  • You can embed variables, expressions, function calls, and apply formatting (e.g., decimal precision, dates).
  • Great for printing, logging, and building dynamic messages.

String slicing

What Is String Slicing?

String slicing means extracting a portion (substring) of a string using its index positions. It’s done using colon (:) notation within square brackets.

text = “Python”
print(text[0:2]) # Output: Py

Syntax

string[start:stop:step]

  • start: the index to begin (inclusive)
  • stop: the index to end (exclusive)
  • step: how many indices to skip (default is 1)

Indexing Recap

Python strings are zero-indexed:

Index: 0 1 2 3 4 5
String: P y t h o n
-6 -5 -4 -3 -2 -1 (negative indexing)

Basic Examples

text = “Python”

print(text[0:4]) # ‘Pyth’ (characters 0 to 3)
print(text[:3]) # ‘Pyt’ (start defaults to 0)
print(text[2:]) # ‘thon’ (to the end)
print(text[:]) # ‘Python’ (whole string)

Using Negative Indices

print(text[-3:]) # ‘hon’
print(text[:-2]) # ‘Pytho’ (up to index -2, exclusive)

Slicing with Steps

print(text[::2]) # ‘Pto’ (every second character)
print(text[::-1]) # ‘nohtyP’ (reversed string)

Real-World Examples

Extract domain from email:

email = “user@example.com”
domain = email[email.index(“@”)+1:]
print(domain) # ‘example.com’

Capitalize only the first letter manually:

word = “python”
result = word[0].upper() + word[1:]
print(result) # ‘Python’

Out-of-Range Slicing

Slicing gracefully handles out-of-bounds indices:

text = “abc”
print(text[0:100]) # ‘abc’ (no error)

Summary:

  • Slicing lets you grab parts of a string with [start:stop:step].
  • It works with both positive and negative indices.
  • Very useful for data cleaning, string manipulation, and reverse operations.

Escape characters and raw strings

What Are Escape Characters?

Escape characters let you insert characters into strings that are otherwise hard to type or have special meaning — like quotes, tabs, newlines, etc.

They all begin with a backslash (\).

Common Escape Characters:

Escape Meaning Example
\’ Single quote ‘It\’s Python’ → It’s Python
\” Double quote “He said, \”Hi\”” → He said, “Hi”
\\ Backslash ‘C:\\path\\file’ → C:\path\file
\n Newline ‘Line1\nLine2’
\t Tab ‘A\tB’ → A B
\r Carriage return ‘123\rABC’ → ABC
\b Backspace ‘A\bB’ → B
\a Bell (system sound) May trigger a beep
\f Form feed Page break in printing
\v Vertical tab Rarely used

Example: Escape in Action

quote = “She said, \”Hello there!\””
print(quote)
# Output: She said, “Hello there!”

path = “C:\\Users\\Name\\Desktop”
print(path)
# Output: C:\Users\Name\Desktop

What Are Raw Strings?

Raw strings treat backslashes (\) literally. Nothing is escaped.

They are prefixed with r or R.

raw_path = r”C:\Users\New\Notes”
print(raw_path)
# Output: C:\Users\New\Notes

No need to double up the \\ when using raw strings!

When to Use Raw Strings

  • Regular expressions (e.g., r”\d+”)
  • File paths on Windows
  • Patterns that include lots of backslashes

import re
pattern = r”\d{3}-\d{2}-\d{4}” # Raw string for regex

Important Note

Even raw strings can’t end with a single backslash — it escapes the quote:

r”test\\” Valid
r”test\” SyntaxError

Summary:

  • Escape characters let you use special symbols like quotes, tabs, and newlines in strings.
  • Raw strings (e.g., r”…”) disable escaping — great for Windows paths and regular expressions.
  • Use escape characters when you need control; use raw strings when you want to avoid escaping every backslash.

Leave a Comment