Codeskill

Learn to code, step by step

String Manipulation: Playing with Text in Python

String manipulation in Python – creating text, slicing it, joining it, formatting it, and using the built-in methods you will reach for most often.

What is a string?

A string is a sequence of characters. Wrap text in single quotes, double quotes, or triple quotes. Single and double quotes work the same; triple quotes can span multiple lines.

Creating strings

greeting = "Hello, Python World!"
multiline_string = """This is
a multiline
string."""

Accessing characters

Python has no separate character type – each element is a one-character string. Use an index in square brackets:

print(greeting[7])  # Outputs 'P'

String slicing

Slice syntax returns a substring:

print(greeting[7:13])  # Outputs 'Python'

Modifying strings

Strings are immutable – you cannot change one in place. Create a new string instead:

new_greeting = greeting.replace("Python", "Programming")
print(new_greeting)  # Outputs 'Hello, Programming World!'

String concatenation

Join strings with +:

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)  # Outputs 'John Doe'

String formatting

f-strings (Python 3.6+) are the easiest way to embed values:

age = 30
message = f"You are {age} years old."
print(message)  # Outputs 'You are 30 years old.'

Common string methods

  • upper(), lower(): change case.
  • strip(): remove leading and trailing whitespace.
  • split(): split on a separator into a list.
  • find(), index(): return the position of a substring.
sentence = "Hello Python world"
print(sentence.upper())          # HELLO PYTHON WORLD
print(sentence.lower())          # hello python world
print(sentence.strip())          # Hello Python world
print(sentence.split(" "))       # ['Hello', 'Python', 'world']
print(sentence.find("Python"))   # 6

Multiline strings

Triple quotes let you write text across several lines:

paragraph = """Python is a powerful language.
It is easy to learn.
This makes it very popular."""

Escape characters

A backslash \ before a character inserts characters you cannot type directly:

text = "He said, \"Python is awesome!\""
print(text)  # Outputs: He said, "Python is awesome!"

Raw strings

Prefix with r to ignore escape sequences. Handy for file paths and regular expressions:

path = r"C:\Program Files\Python"
print(path)  # Outputs: C:\Program Files\Python

Membership test

Check whether a substring exists with in:

print("Python" in greeting)  # Outputs: True

String iteration

Strings are iterable – loop over each character:

for char in greeting:
    print(char)
PreviousDictionaries and Sets: Python’s Powerful Collections