0%

6- Strings in Python

A string is a sequence of characters wrapped in quotes. It can hold a single letter, a whole sentence, or an entire book. Strings are how Python understands human language.

Words matter. In programming, almost everything you read or write is a string. A username from a login form. A tweet from a social media app. A paragraph in a document. The name of a product in an online store. Even the code you write is processed as strings by the compiler. A string is simply a sequence of characters (letters, numbers, spaces, punctuation) enclosed in quotes. Python does not care what you write inside. It just remembers the sequence exactly as you typed it. Strings are one of the most common data types in Python. You will use them in almost every program you write.

🕯️ Magic Note

The name “string” comes from a metaphor: think of characters as beads on a string. Each bead (character) has a position. You can move along the string, pick a specific bead, count the beads, or tie strings together. This is why we call text manipulation “string operations.”

Creating Strings: Three Ways to Quote
Python gives you three ways to create strings. Each has its own purpose.
Quote TypeExampleBest For
Single quotes (‘)‘Hello’Most common, simple strings
Double quotes (“)“Hello”Strings that contain single quotes inside
Triple quotes (”’ or “””)”’Hello”’Multi-line strings

Python

# Different ways to create strings

single = ‘Hello, Python!’

double = “Hello, Python!”

triple_single = ”’This string

can span multiple

lines easily.”’

triple_double = “””So can this one.”””

# Double quotes are useful when you need apostrophes

message = “It’s a beautiful day” # No need to escape the apostrophe

# Same string with single quotes would need an escape: ‘It\’s a beautiful day’

💡 Single and double quotes are completely interchangeable. Python does not prefer one over the other. Choose whichever makes your string easier to write and read. Most Python programmers use single quotes for most strings and double quotes for strings that contain apostrophes or for documentation strings (docstrings).
Empty Strings
An empty string contains nothing. Not a space, not a letter. Just two quotes with nothing between them. Empty strings are useful as placeholders or for building strings gradually.

Python

empty1 = ”

empty2 = “”

empty3 = “””””” # Triple quotes can also be empty

print(len(empty1)) # 0 (length is zero)

print(empty1 == “”) # True

Escape Sequences: Special Characters in Strings
What if you need to put a quote inside a string that uses the same quotes? Or add a new line? Or a tab? Python uses escape sequences for this. An escape sequence starts with a backslash \ followed by a character.
Escape SequenceWhat It DoesExample Output
\Single quote‘It\’s magic’ → It’s magic
\Double quote“She said \”Hello\”” → She said “Hello”
\nNew line“Line1\nLine2” → Line1 (new line) Line2
\tTab (indent)“Name:\tAli” → Name: Ali
\\Backslash itself“Path: C:\\Users” → Path: C:\Users
\rCarriage return“Hello\rWorld” → World (overwrites Hello)
\bBackspace“Hello\bWorld” → HellWorld

Python

# Escape sequences in action

print(‘It\’s a secret spell’) # It’s a secret spell

print(“She whispered \”Conjure\””) # She whispered “Conjure”

print(“First line\nSecond line”) # First line

# Second line

print(“Column1\tColumn2”) # Column1 Column2

print(“C:\\Users\\Feloriya”) # C:\Users\Feloriya

🕯️ Magic Note

If you have many backslashes and do not want to escape them all (like in file paths or regular expressions), you can use a raw string. Put an r before the opening quote: r”C:\Users\Feloriya”. In raw strings, backslashes are treated as normal characters.

Python

# Raw strings ignore escape sequences

normal = “C:\\Users\\Feloriya\\Desktop”

raw = r”C:\Users\Feloriya\Desktop”

print(normal == raw) # True (they contain the same characters)

print(raw) # C:\Users\Feloriya\Desktop

String Length with len()
The len() function returns the number of characters in a string. Spaces, punctuation, and escape sequences (that produce one character) all count as one character.

Python

name = “Feloriya”

print(len(name)) # 8 (F e l o r i y a)

sentence = “Hello, World!”

print(len(sentence)) # 13 (including comma, space, exclamation)

empty = “”

print(len(empty)) # 0

# Escape sequences count as ONE character

newline_str = “Hello\nWorld”

print(len(newline_str)) # 11 (H e l l o \n W o r l d → \n is one character)

💡 The len() function works on all sequences, not just strings. You can use it on lists, tuples, dictionaries, and sets as well. It is one of the most frequently used functions in Python.
String Concatenation: Joining Strings Together
Concatenation means joining strings end to end. Use the + operator to combine strings.

Python

first = “Hello”

second = “World”

message = first + ” ” + second

print(message) # Hello World

# You can concatenate directly without variables

full = “Python ” + “is ” + “magical”

print(full) # Python is magical

🕯️ Magic Note

You cannot concatenate a string with a non-string directly. “Score: ” + 100 will raise a TypeError. You must convert the number to a string first using str(): “Score: ” + str(100).

Python

# Converting numbers to strings for concatenation

age = 25

message = “I am ” + str(age) + ” years old”

print(message) # I am 25 years old

# This would cause an error:

# message = “I am ” + age + ” years old” # TypeError

String Repetition with *
The * operator repeats a string a specified number of times. This is surprisingly useful for creating separators, patterns, or padding.

Python

echo = “ha” * 3

print(echo) # hahaha

separator = “-” * 20

print(separator) # ——————–

spaces = ” ” * 10

print(spaces + “Indented”) # Indented

# Zero or negative numbers produce an empty string

nothing = “abc” * 0

print(nothing) # (empty string)

Accessing Characters by Index
Strings are sequences. Each character has a position, called an index. The first character is at index 0, the second at index 1, and so on. You can access a specific character using square brackets []. Python also supports negative indices. -1 is the last character, -2 is the second last, and so on.

Python

word = “Python”

# Index: 0 1 2 3 4 5

# Character: P y t h o n

# Negative: -6 -5 -4 -3 -2 -1

print(word[0]) # P

print(word[1]) # y

print(word[5]) # n

print(word[-1]) # n (last character)

print(word[-2]) # o (second last)

print(word[-6]) # P (first character)

⚠️ Attempting to access an index that does not exist raises an IndexError. For a string of length 6, valid indices are -6 through 5. word[6] or word[-7] will cause an error.
String Slicing: Extracting Substrings
Slicing allows you to extract a portion (a slice) of a string. The syntax is string[start:end:step]. – start is the index where the slice begins (included) – end is the index where the slice ends (excluded) – step is the interval between characters (optional, default is 1) If you omit start, it defaults to the beginning. If you omit end, it defaults to the end.

Python

text = “Programming”

# Indices: 0 1 2 3 4 5 6 7 8 9 10

# Char: P r o g r a m m i n g

print(text[0:4]) # Prog (indices 0,1,2,3)

print(text[4:8]) # ramm (indices 4,5,6,7)

print(text[:4]) # Prog (start omitted → beginning)

print(text[8:]) # ing (end omitted → end)

print(text[:]) # Programming (entire string)

print(text[::2]) # Pormn (every second character)

print(text[::-1]) # gnimmargorP (reverse string)

🕯️ Magic Note

The slice [::-1] is a classic trick to reverse a string. It starts at the end (because step is -1) and moves backward to the beginning. This works for any sequence in Python.

Strings Are Immutable
This is one of the most important concepts about strings in Python. Strings are immutable. They cannot be changed after they are created. When you think you are changing a string, you are actually creating a brand new string and assigning it to the variable. The original string remains unchanged (and may be garbage collected if nothing references it).

Python

name = “Feloriya”

# This does NOT work (strings are immutable)

# name[0] = “M” # TypeError: ‘str’ object does not support item assignment

# This creates a NEW string and reassigns it

name = “M” + name[1:] # Creates “Meloriya”

print(name) # Meloriya

# The original “Feloriya” is now gone (or ready for garbage collection)

⚠️ Immutability means every string operation that modifies the string (like .upper(), .replace(), or concatenation) creates a new string. If you are doing many string operations in a loop, this can be inefficient. For heavy string manipulation, consider using lists or io.StringIO.
String Comparison
Strings can be compared using the same operators as numbers. Python compares strings lexicographically (dictionary order) based on the Unicode values of characters.

Python

print(“apple” == “apple”) # True

print(“apple” == “Apple”) # False (case-sensitive)

print(“apple” != “orange”) # True

print(“apple” < “banana”) # True (‘a’ comes before ‘b’)

print(“Apple” < “apple”) # True (uppercase letters have lower Unicode values)

print(“10” < “2”) # True (string comparison: ‘1’ vs ‘2’)

💡 String comparison is case-sensitive. If you need case-insensitive comparison, convert both strings to the same case using .lower() or .upper(): str1.lower() == str2.lower().
Checking Substrings with in and not in
Use the in operator to check if a substring exists inside a string. This is much more readable than searching manually.

Python

sentence = “The magic of Python”

print(“magic” in sentence) # True

print(“Java” in sentence) # False

print(“python” in sentence) # False (case-sensitive)

# Using not in

print(“Java” not in sentence) # True

# Useful in conditionals

if “Python” in sentence:

print(“Python is mentioned!”)

Strings and User Input
The input() function always returns a string, even if the user types a number. You must convert it if you need a different type.

Python

# input() always returns a string

user_input = input(“Enter something: “)

print(type(user_input)) # <class ‘str’>

# Convert to integer if needed

age_str = input(“Enter your age: “)

age_int = int(age_str)

# Or combine in one line (but be careful with invalid input)

height = float(input(“Enter your height in meters: “))

Common Mistakes with Strings
  • Mixing quotes without escaping: ‘It’s magic’ causes SyntaxError. Use double quotes or escape: “It’s magic” or ‘It\’s magic’
  • Forgetting that strings are immutable: trying to change a character directly with s[0] = ‘a’ causes TypeError
  • Using + with non-strings: “Score: ” + 100 causes TypeError. Convert first: “Score: ” + str(100)
  • Off-by-one errors in slicing: s[:5] gives indices 0 through 4 (not 5)
  • Comparing strings with == when case differs: “hello” == “Hello” is False
  • Accessing index out of range: s[10] when len(s) is 5 causes IndexError
  • Forgetting that input() always returns a string, even for numbers
⚠️ A common pitfall is comparing a string from input() directly to a number. input() returns a string, so user_input == 10 is always False because a string never equals an integer. Either convert the input to an integer with int() or compare to a string: user_input == “10”.
Check Your Understanding
  • How do you create a string that contains a single quote? Give two ways.
  • What is the output of len(“Hello\nWorld”)?
  • How do you get the last character of a string without knowing its length?
  • Write a slice that extracts characters from index 2 to 5 of a string.
  • What happens if you try to change a character in a string with s[0] = ‘x’?
  • What does the expression “10” < “2” evaluate to? Why?

⚡ Whisper

A string is a thread of whispers sewn together. Each character holds a small piece of meaning. You can count them, slice them, join them with other threads, or ask if a certain word hides within. But you cannot unweave a single thread without cutting the whole strand. Strings are fragile in their immutability, yet strong in their persistence. Treat them with care. What you write in quotes becomes a message that Python will carry faithfully to the world. Choose your words well. They matter more than you think.

Related posts