Strings
What is a String?
A string is a sequence of characters used to represent text in programming languages.
Strings are essential for handling user input, displaying information, and manipulating
text data in programs.
Strings and Lists: A Connection
Both are sequences in Python.
Both support indexing, slicing, and iteration.
Key difference: Strings are immutable, lists are mutable.
Feature List String
Mutable Yes No
Indexing Yes Yes
Slicing Yes Yes
Methods Many Many
Indexing and Slicing: Strings vs Lists
my_list = [1, 2, 3, 4]
my_str = "abcd"
print(my_list[1]) # 2
print(my_str[1]) # 'b'
print(my_list[1:3]) # [2, 3]
print(my_str[1:3]) # 'bc'
Indexing and Slicing: Strings vs Lists
Each character in a string has an index. Extract substrings using slicing:
word = "Python"
print(word[0]) # 'P'
print(word[-1]) # 'n'
text = "Programming"
print(text[0:6]) # 'Progra'
print(text[3:]) # 'gramming'
print(text[:5]) # 'Progr'
Slicing Tricks with Strings
Reverse a string:
word = "Python"
print(word[::-1]) # 'nohtyP'
Extract every other character:
data = "abcdefg"
print(data[::2]) # 'aceg'
String Immutability
You cannot change a character in a string directly.
You can change elements in a list.
Operations that seem to "change" a string actually create a new string.
my_str = "hello"
# my_str[0] = 'y' # Error!
my_list = [1, 2, 3]
my_list[0] = 9 # Works
original = "hello"
modified = [Link]("h", "y")
print(original) # 'hello'
print(modified) # 'yello'
Reminder: String Concatenation & Repetition
Combine strings using + or * :
greeting = "Hello, " + "World!"
repeat = "ha" * 3 # 'hahaha'
Reminder: String Formatting
Three common ways to format strings:
name = "Bob"
age = 20
print(f"My name is {name} and I am {age} years old.")
print("My name is %s and I am %d years old." % (name, age))
print("My name is {} and I am {} years old.".format(name, age))
Useful String Methods
Strings have many useful methods:
upper() , lower() , replace() , find() , split() , strip() , startswith() ,
endswith()
text = " Python is fun! "
print([Link]()) # 'Python is fun!'
print([Link]()) # ' PYTHON IS FUN! '
print([Link]("fun", "awesome")) # ' Python is awesome! '
print([Link]()) # ['Python', 'is', 'fun!']
print([Link]('fun')) # 10
Checking String Content
text = "123abc"
print([Link]()) # False
print([Link]()) # False
print("123".isdigit()) # True
Escape Characters & Multiline Strings
Escape characters allow you to include special characters in strings:
Escape Meaning
\n Newline
\t Tab
\\ Backslash
\' Single quote
\" Double quote
Example:
print("Line1\nLine2")
Shared Features: Membership, Length, Iteration
Check if an element or character exists:
print('a' in "cat") # True
print(2 in [1, 2, 3]) # True
Use len() for both:
print(len("hello")) # 5
print(len([1, 2, 3])) # 3
You can loop through both strings and lists:
for char in "hello":
print(char)
for item in [1, 2, 3]:
print(item)
Looping Through Strings for Useful Data (No Built-in Methods)
Here are some examples of how you can use loops to analyze or process strings
without using built-in string methods:
Count the number of uppercase letters:
text = "Hello World! Python 2025"
count = 0
for char in text:
if 'A' <= char <= 'Z':
count += 1
print("Uppercase letters:", count) # 3
Count the number of digits:
text = "Room 101, Floor 2"
digit_count = 0
for char in text:
if '0' <= char <= '9':
digit_count += 1
print("Digits:", digit_count) # 4
Count the number of vowels in a string:
text = "sky"
vowels ="aeiouAEIOU" vowel_count = 0
for char in text:
if char in vowels: vowel_count += 1
print("Number of vowels:", vowel_count)
Get a list of floats from a single input statement:
# Get a string of numbers from the user (all values are strings at first)
num_string = input("Enter numbers separated by spaces: ")
# Split the string into a list of substrings
str_list = num_string.split()
float_list = []
for s in str_list:
float_list.append(float(s)) # Convert each string to a float and add to the list
print(float_list)
We need to use a loop to convert each string to a float, because split() only separates
the text—it does not change the data type.
If we tried to use float(str_list), it would give an error, because float() expects a single
string, not a list.