Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Working with Strings in Python

1. Introduction

Strings in Python are immutable sequences of Unicode characters. They are one of the most commonly used data types and provide various functionalities to manipulate text.

2. String Creation

Strings can be created in Python using single quotes, double quotes, or triple quotes for multi-line strings.

single_quote_string = 'Hello, World!'
double_quote_string = "Hello, World!"
triple_quote_string = """This is a
multi-line string."""

3. String Manipulation

Common string manipulation techniques include:

  • Concatenation: Combining strings using the + operator.
  • Repetition: Repeating strings using the * operator.
  • Slicing: Accessing parts of a string using indices.
greeting = "Hello"
name = "Alice"
combined = greeting + " " + name  # "Hello Alice"
repeated = greeting * 3  # "HelloHelloHello"
sub_string = greeting[1:4]  # "ell"

4. Common String Methods

Python provides numerous built-in methods for string manipulation:

  • str.lower(): Converts a string to lowercase.
  • str.upper(): Converts a string to uppercase.
  • str.strip(): Removes leading and trailing whitespace.
  • str.replace(old, new): Replaces occurrences of a substring.
  • str.split(separator): Splits a string into a list.
  • str.join(iterable): Joins elements of an iterable into a string.
text = "   Python is fun!   "
print(text.lower())  # "   python is fun!   "
print(text.strip())  # "Python is fun!"
print(text.replace("fun", "awesome"))  # "   Python is awesome!   "
words = text.split()  # ['Python', 'is', 'fun!']
joined = ", ".join(words)  # "Python, is, fun!"

5. String Formatting

Formatting strings can be done using three primary methods:

  • f-strings (Python 3.6+): Embedding expressions inside string literals.
  • str.format(): More traditional method of formatting strings.
  • Percent formatting: Old-style formatting using % operator.
name = "Alice"
age = 30
# f-strings
print(f"{name} is {age} years old.")

# str.format()
print("{} is {} years old.".format(name, age))

# Percent formatting
print("%s is %d years old." % (name, age))

6. FAQ

What is the difference between single and double quotes?

In Python, single and double quotes can be used interchangeably to define strings. The choice often depends on the need to use quotes within the string.

Are strings mutable in Python?

No, strings in Python are immutable. Once a string is created, it cannot be modified. Any operation that alters a string will create a new string.

How can I check if a substring exists within a string?

You can use the in keyword to check for a substring:

text = "Hello, World!"
print("Hello" in text)  # True