Strings

Text in Python — how to create it, reach into it, combine it, and reshape it.

Introduction

A string is a sequence of characters, created by wrapping text in single quotes, double quotes, or triple quotes. Triple quotes are the only way to let a string span multiple lines naturally.

s1 = 'ByteWise'
s2 = "ByteWise"
s3 = """Line one
Line two"""
print(s3)
Line one Line two

Strings also support escape sequences — a backslash followed by a character that means something special, like \n for a newline or \t for a tab.

print("Byte\nWise")
print("Byte\tWise")
print("She said \"hi\"")
Byte Wise Byte Wise She said "hi"

Strings are immutable — like every other sequence type, len() tells you how many characters it has, but you can't reassign a single character in place (more on that in Methods).

print(len("ByteWise"))
8

Indexing & Slicing

Each character has a position, or index, starting at 0 from the left. Negative indices count backward from the end, starting at -1.

s = "ByteWise"
print(s[0])
print(s[-1])
print(s[3])
B e e

Asking for an index that doesn't exist raises an IndexError:

print(s[20])
IndexError: string index out of range

Slicing pulls out a whole chunk with s[start:stop:step]. The stop index is never included, and every part is optional.

s = "ByteWise"
print(s[0:4])
print(s[2:])
print(s[:5])
print(s[::-1])
Byte teWise ByteW esiWetyB

Slicing out of bounds doesn't raise an error — it just returns as much as exists, even an empty string:

print("Byte"[10:20])

Operators

Concatenation (+) joins two strings together. Only strings can be added to strings — mixing in a number raises a TypeError.

print("Byte" + "Wise")
print("Byte" + 5)
ByteWise TypeError: can only concatenate str (not "int") to str

Replication (*) repeats a string a number of times.

print("re" * 3)
rererere

Membership (in / not in) checks whether one string appears inside another.

print("Byte" in "ByteWise")
print("byte" not in "ByteWise")
True True

Comparison operators compare strings character by character using their underlying character codes, not their length.

print("a" > "z")
print("Bro" < "x")
False True

Methods

String methods are called with string.method(). None of them modify the original string — since strings are immutable, they always return a new one.

Case methodsupper(), lower(), capitalize(), and title() change letter casing.

print("bytewise".upper())
print("BYTEWISE".lower())
print("hello there".title())
BYTEWISE bytewise Hello There

Checks — methods like isalpha(), isdigit(), and isalnum() return a bool describing what's in the string.

print("Johan".isalpha())
print("12345".isdigit())
print("Byte123".isalnum())
True True True

Cleaning & splittingstrip() removes leading/trailing whitespace, split() breaks a string into a list of pieces, and join() does the reverse.

print("  tidy me  ".strip())
print("one two three".split())
print("-".join(["a", "b", "c"]))
tidy me ['one', 'two', 'three'] a-b-c

Searching & replacingfind() returns the first index of a substring (or -1 if missing), count() tallies occurrences, and replace() swaps text out.

print("ByteWise".find("e"))
print("abracadabra".count("ab"))
print("Bytevise".replace("v", "W"))
3 2 ByteWise

startswith() and endswith() check the beginning or end of a string and return a bool.

print("ByteWise".startswith("Byte"))
print("ByteWise".endswith("Wise"))
True True