Skip to main content

Strings

Strings are an essential data type in Python, used to represent text data. They are sequences of characters enclosed within single (') or double (") quotes.

message = "Hello, World!"
alternative = 'Python is fun!'

An empty string is simply "" or '', containing zero characters.

Basic String Operations

Concatenation

Combine strings using the + operator:

greeting = "Hello, " + "Alice!"
print(greeting) # Output: Hello, Alice!

Repetition

Repeat strings using the * operator:

laugh = "Ha" * 3
print(laugh) # Output: HaHaHa

Length

Find the length of a string using the len() function:

length = len("Python")
print(length) # Output: 6

String Indexing and Slicing

Strings are immutable sequences of characters, meaning individual characters cannot be changed after the string is created. However, you can access and manipulate parts of strings.

Accessing Characters

  • Zero-Based Indexing: The first character is at index 0.
fruit = "Banana"
print(fruit[0]) # Output: 'B'
print(fruit[3]) # Output: 'a'
  • Negative Indexing: Access characters from the end using negative indices.
print(fruit[-1])  # Output: 'a' (last character)
print(fruit[-3]) # Output: 'a'

Slicing Strings

Extract substrings using the slice syntax string[start:end]:

print(fruit[0:3])   # Output: 'Ban' (characters at indices 0,1,2)
print(fruit[2:]) # Output: 'nana' (from index 2 to end)
print(fruit[:4]) # Output: 'Bana' (from start to index 3)
  • Slice Parameters:
    • start: Starting index (inclusive). Defaults to 0 if omitted.
    • end: Ending index (exclusive). Defaults to len(string) if omitted.

Examples

text = "Mangosteen"
print(text[1:4]) # Output: 'ang'
print(text[:5]) # Output: 'Mango'
print(text[5:]) # Output: 'steen'

Modifying Strings

While strings are immutable, you can create new strings based on existing ones.

Creating New Strings

message = "Hello, worzd!"
# Incorrect character at index 10 ('z')

# Cannot do: message[10] = 'l' # Raises TypeError

# Correct approach:
new_message = message[:10] + 'l' + message[11:]
print(new_message) # Output: 'Hello, world!'

Finding Substrings

Use the index() method to find the position of a substring:

print("winter".index("t"))    # Output: 3
print("winter".index("ter")) # Output: 3
  • Note: If the substring is not found, index() raises a ValueError.

Checking Substring Presence

Use the in keyword:

print("Dragons" in "Mythical creatures")  # Output: False
print("cat" in "concatenate") # Output: True

String Methods

Python provides numerous methods for string manipulation.

Transforming Strings

upper() And lower()

Convert strings to uppercase or lowercase:

name = "Alice"
print(name.upper()) # Output: 'ALICE'
print(name.lower()) # Output: 'alice'

strip(), lstrip(), rstrip()

Remove whitespace:

text = "  Hello, World!  "
print(text.strip()) # Output: 'Hello, World!'
print(text.lstrip()) # Output: 'Hello, World! '
print(text.rstrip()) # Output: ' Hello, World!'

Analyzing Strings

count(substring)

Count occurrences of a substring:

print("banana".count("a"))  # Output: 3

endswith(substring)

Check if a string ends with a given substring:

filename = "report.pdf"
print(filename.endswith(".pdf")) # Output: True

isnumeric()

Check if a string consists only of numbers:

num = "12345"
print(num.isnumeric()) # Output: True

not_num = "123abc"
print(not_num.isnumeric()) # Output: False

Splitting and Joining Strings

split()

Split a string into a list of substrings:

sentence = "This is a test"
words = sentence.split()
print(words) # Output: ['This', 'is', 'a', 'test']
  • Custom Delimiter:
data = "apple,banana,cherry"
fruits = data.split(',')
print(fruits) # Output: ['apple', 'banana', 'cherry']

join()

Join a list of strings into a single string:

words = ['This', 'is', 'a', 'sentence']
sentence = ' '.join(words)
print(sentence) # Output: 'This is a sentence'

Formatting Strings

Formatting strings allows you to embed variables and expressions into strings with minimal syntax. Python offers several methods for string formatting.

The format() Method

Basic Formatting

name = "Bob"
age = 25
message = "Name: {}, Age: {}".format(name, age)
print(message) # Output: 'Name: Bob, Age: 25'

Named Placeholders

message = "Coordinates: Latitude={lat}, Longitude={lon}".format(lat=51.5074, lon=0.1278)
print(message) # Output: 'Coordinates: Latitude=51.5074, Longitude=0.1278'

Formatting Numbers

Fixed Decimal Places
price = 8.126
print("Price: ${:.2f}".format(price)) # Output: 'Price: $8.13'
Alignment and Width
for x in range(1, 5):
print("{:>2} squared is {:>3}".format(x, x*x))

Output:

 1 squared is   1
2 squared is 4
3 squared is 9
4 squared is 16
  • {:>2}: Right-align within 2 spaces.
  • {:<3}: Left-align within 3 spaces.

Formatted String Literals (f-Strings)

Introduced in Python 3.6, f-Strings provide a concise and readable way to embed expressions inside string literals using minimal syntax.

Basic Usage

name = "Alice"
age = 30
message = f"Name: {name}, Age: {age}"
print(message) # Output: 'Name: Alice, Age: 30'
  • Place an f or F before the opening quote.
  • Include variables or expressions inside curly braces {}.

Embedding Expressions

result = f"5 multiplied by 2 is {5 * 2}"
print(result) # Output: '5 multiplied by 2 is 10'

Formatting Numbers with f-Strings

price = 8.126
print(f"Price: ${price:.2f}") # Output: 'Price: $8.13'
  • Syntax: {variable:format_spec}
  • Format Specifications:
    • .2f: Fixed-point notation with two decimal places.

Alignment and Width

for x in range(1, 5):
print(f"{x:>2} squared is {x*x:>3}")

Output:

 1 squared is   1
2 squared is 4
3 squared is 9
4 squared is 16
  • {x:>2}: Right-align x within 2 spaces.
  • {x*x:>3}: Right-align x*x within 3 spaces.

Multi-line f-Strings

name = "Bob"
occupation = "Builder"
profile = f"""
Name : {name}
Occupation: {occupation}
"""
print(profile)

Output:

Name      : Bob
Occupation: Builder

Advanced Formatting with f-Strings

Temperature Conversion Table Using f-Strings

print(f"{'F':>3} F | {'C':>6} C")
for fahrenheit in range(0, 101, 10):
celsius = (fahrenheit - 32) * 5/9
print(f"{fahrenheit:>3} F | {celsius:>6.2f} C")

Output:

  F F |      C C
0 F | -17.78 C
10 F | -12.22 C
20 F | -6.67 C
30 F | -1.11 C
40 F | 4.44 C
50 F | 10.00 C
60 F | 15.56 C
70 F | 21.11 C
80 F | 26.67 C
90 F | 32.22 C
100 F | 37.78 C

Benefits of f-Strings

  • Readability: Directly embed variables and expressions.
  • Performance: Faster than .format() method in most cases.
  • Simplicity: Less verbose and easier to write.

Practical Applications

Updating Email Domains

Suppose your organization changed its email domain, and you need to update email addresses.

def replace_domain(email, old_domain, new_domain):
if "@" + old_domain in email:
index = email.index("@" + old_domain)
new_email = email[:index] + "@" + new_domain
return new_email
return email

# Example usage:
old_email = "user@olddomain.com"
new_email = replace_domain(old_email, "olddomain.com", "newdomain.com")
print(new_email) # Output: 'user@newdomain.com'

Handling User Input

answer = input("Do you accept the terms? (yes/no): ").strip().lower()

if answer == "yes":
print("Terms accepted.")
elif answer == "no":
print("Terms declined.")
else:
print("Invalid response.")

Using f-Strings in Functions

def generate_greeting(name, age):
return f"Welcome, {name}! You are {age} years old."

print(generate_greeting("Alice", 30))
# Output: 'Welcome, Alice! You are 30 years old.'

Summary

  • Access individual characters using indexing.
  • Extract substrings using slicing.
  • Transform strings with methods like upper(), lower(), and strip().
  • Analyze strings using count(), endswith(), and isnumeric().
  • Split and join strings for flexible text processing.
  • Format strings elegantly with the format() method and f-Strings.