A string is a sequence of characters, and in Python it is one of the most frequently used data types. Strings represent text: names, addresses, sentences, passwords, file contents, and much more. Every program that communicates with a human user does so through strings, both when reading input and when displaying output. In Python, a string is written by enclosing characters in single quotes, double quotes or triple quotes, and it is stored as an immutable object of the str type.
Because strings are sequences, they support all the sequence operations: indexing, which extracts a single character, slicing, which extracts a substring, and iteration, which visits each character one by one. Strings also support the concatenation operator +, which joins two strings, and the repetition operator *, which repeats a string several times. Membership tests with the in operator check whether a character or substring exists inside a string.
Beyond these core operations, Python's str class provides a rich set of built-in methods for string processing, such as upper(), lower(), strip(), split(), join(), replace(), find() and count(). These methods make text processing concise and readable. This chapter also explains the escape characters used to represent special characters inside strings, and it applies the looping skills from the previous chapter to write character-by-character string-processing programs.
Strings can be created by enclosing text in quotes. All three quoting styles are valid, and the choice depends on the content of the string.
s1 = 'Hello' # single quotes
s2 = "World" # double quotes
s3 = '''A multi-line
string''' # triple quotes
s4 = "" # empty string
Single and double quotes are interchangeable. Triple quotes allow strings to span multiple lines and can contain both single and double quotes. An empty string contains zero characters.
A subtle point: Python automatically concatenates adjacent string literals. For example, "Py" "thon" is the single string "Python".
Since a string is a sequence, each character has a position called an index. Python uses zero-based indexing: the first character is at index 0. Negative indices count from the end, with -1 being the last character.
word = "PYTHON"
print(word[0]) # 'P'
print(word[3]) # 'H'
print(word[-1]) # 'N'
print(word[-2]) # 'O'
Slicing extracts a substring. The slice word[start:end] returns the characters from index start up to, but not including, index end.
word = "PYTHON"
print(word[0:4]) # 'PYTH'
print(word[2:]) # 'THON' (from 2 to end)
print(word[:3]) # 'PYT' (from start to 2)
print(word[1:5:2]) # 'YH' (start 1, stop 5, step 2)
print(word[::-1]) # 'NOHTYP' (reversed string)
Remember: the end index in a slice is always exclusive, and a step can be used to skip characters or reverse the string.
Traversing means visiting each character of the string in turn. This is usually done with a for loop.
word = "Python"
for ch in word:
print(ch, end=" ")
Traversal is the basis of many string-processing programs, such as counting vowels, counting occurrences of a letter, or checking whether a string is a palindrome.
Python provides several operators that work on strings.
print("Py" + "thon") # Python
print("Go " * 2) # Go Go
print("Py" in "Python") # True
print("x" not in "Python") # True
Several built-in functions work with strings.
s = "hello"
print(len(s)) # 5
print(max(s)) # 'o'
print(min(s)) # 'e'
print(str(123)) # '123'
Python strings have many methods that create new, processed strings. Because strings are immutable, these methods return a new string rather than modifying the original.
s = "hello World"
print(s.upper()) # HELLO WORLD
print(s.lower()) # hello world
print(s.title()) # Hello World
print(s.swapcase()) # HELLO wORLD
s = " Python is fun "
print(s.strip()) # 'Python is fun'
print("banana".count("a")) # 3
print("hello".find("l")) # 2
print("hello".replace("l", "L")) # heLLo
print("Hello".startswith("He")) # True
print("123".isdigit()) # True
print("Hi there".split(" ")) # ['Hi', 'there']
print("-".join(["a", "b", "c"])) # a-b-c
Escape sequences are backslash combinations that represent special characters inside a string. They allow characters that are hard to type directly.
| Escape | Meaning |
|---|---|
| \n | Newline |
| \t | Tab |
| \\ | Backslash |
| \' | Single quote |
| \" | Double quote |
print("Line1\nLine2") # prints on two lines
print("Column1\tColumn2")
print("She said \"Hi\"")
s = input("Enter a sentence: ").lower()
vowels = 0
consonants = 0
for ch in s:
if ch.isalpha():
if ch in "aeiou":
vowels += 1
else:
consonants += 1
print("Vowels:", vowels, "Consonants:", consonants)
s = input("Enter a word: ").lower()
if s == s[::-1]:
print("It is a palindrome")
else:
print("It is not a palindrome")
s = "Python is powerful"
words = s.split()
reversed_sentence = " ".join(words[::-1])
print(reversed_sentence) # powerful is Python
| Operator | Operation | Example Result |
|---|---|---|
| + | Concatenation | "Py"+"thon" = "Python" |
| * | Repetition | "Ha"*3 = "HaHaHa" |
| in | Membership | "Py" in "Python" = True |
| not in | Non-membership | "x" not in "Python" = True |
| [] | Indexing | "PYTHON"[0] = 'P' |
| [:] | Slicing | "PYTHON"[1:4] = "YTH" |
| Method | Purpose | Example |
|---|---|---|
| upper() | Convert to uppercase | "hi".upper() = "HI" |
| lower() | Convert to lowercase | "HI".lower() = "hi" |
| strip() | Remove surrounding spaces | " hi ".strip() = "hi" |
| find(sub) | Index of first occurrence | "hello".find("l") = 2 |
| count(sub) | Number of occurrences | "banana".count("a") = 3 |
| split(sep) | Split into list | "a b".split(" ") = ['a','b'] |
| join(list) | Join list into string | "-".join(["a","b"]) = "a-b" |
Strings are the primary way Python represents and processes text, and they combine the simplicity of a sequence with a powerful library of methods. Indexing and slicing provide precise access to characters and substrings, operators such as concatenation, repetition and membership build and inspect strings, and the extensive set of methods handles case conversion, searching, trimming, splitting and joining with ease. Because strings are immutable, every operation returns a new string, which is a crucial fact for correct programming. With strings mastered, the next chapter turns to lists, Python's most flexible data structure, which shares many of the sequence concepts introduced here.