Remember
A string is an immutable sequence of characters. Indexing selects a character; an operation that changes text returns a new string.
A string is an immutable sequence of characters. Indexing selects a character; an operation that changes text returns a new string.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
name = 'Ada'
first = name[0]
greeting = "Hello, " + name
print(first)
print(greeting)Top-level scope
'Ada'Object 2 · str'A'Object 3 · str'Hello, Ada'A string is an immutable sequence of characters. Indexing selects a character; an operation that changes text returns a new string.
(no output)
What do you expect this program to print?
text = "cat"
INDEX 0 1 2
+---+ +---+ +---+
CHARACTER | c | | a | | t |
+---+ +---+ +---+
text[0] --> "c"Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
name = 'Ada'
first = name[0]
greeting = "Hello, " + name
print(first)
print(greeting)Top-level scope
'Ada'Object 2 · str'A'Object 3 · str'Hello, Ada'The example has finished. Compare the final output with the values and references above.
A Hello, Ada
What do you expect this program to print?
name = 'Ada'
first = name[0]
greeting = "Hello, " + name
print(first)
print(greeting)A string in Python is a sequence of characters enclosed in single ('), double ("), or triple quotes (''' or """).
'Hello, World!'
"Hello, World!"
Strings are used to store text-based information such as names, messages, or any human-readable data.
You can create a string using single or double quotes interchangeably:
name = 'Arjun'
message = "Hello, World!"
If your string contains quotes inside, use the other type to avoid syntax errors:
quote = "It's a beautiful day"
alt_quote = 'He said, "Hi!"'
Use triple quotes when you want to write strings across multiple lines.
poem = """Roses are red,
Violets are blue,
Python is great,
And so are you."""
In Python, you can access individual characters in a string using indexing. Each character in the string has a position, called an index, which starts from 0 for the first character and increases by one for each subsequent character.
Here's how you can use positive indexing to access characters from the beginning:
greeting = "Hello"
print(greeting[0]) # H (first character)
print(greeting[4]) # o (fifth character)
H
o
Python also supports negative indexing, which allows you to access characters from the end of the string. The last character has an index of -1, the second last is -2, and so on.
greeting = "Hello"
print(greeting[-1]) # o (last character)
print(greeting[-2]) # l (second last character)
o
l
This flexibility makes it easy to access both ends of a string without needing to know its exact length.
Slicing helps extract parts of a string using the syntax string[start:end].
text = "Python"
print(text[0:2]) # Py
print(text[2:]) # thon
print(text[:3]) # Pyt
print(text[-3:]) # hon
Py
thon
Pyt
hon
Strings in Python are immutable. This means once created, they cannot be changed in place.
word = "Python"
word[0] = "J" # This will raise a TypeError
Traceback (most recent call last):
File "main.py", line 2, in
word[0] = "J" # This will raise a TypeError
TypeError: 'str' object does not support item assignment
Python provides several built-in methods to work with strings:
lower(): Converts all characters to lowercaseupper(): Converts all characters to uppercasestrip(): Removes leading and trailing whitespacereplace(old, new): Replaces substringsplit(): Splits the string into a listjoin(): Joins elements of a list with a string separators = " Learn Python "
print(s.strip()) # 'Learn Python'
print(s.lower()) # ' learn python '
print(s.replace("Python", "Java")) # ' Learn Java '
Learn Python
learn python
Learn Java
For complete set of string methods in Python, you may refer String methods.
In Python, you can insert variables directly into strings using f-strings (formatted string literals). This makes it easy to construct readable and dynamic messages.
name = "Arjun"
age = 25
print(f"My name is {name} and I am {age} years old.")
My name is Arjun and I am 25 years old.
Python allows you to check whether a certain substring exists within a string using the in and not in keywords. These return a boolean value — True or False.
msg = "Welcome to Python"
print("Python" in msg) # True, because "Python" is in the string
print("Java" not in msg) # True, because "Java" is not in the string
True
True
Since strings are sequences of characters, you can loop through them using a for loop. Each iteration gives you one character from the string.
for char in "Hi":
print(char)
H
i
You can find out how many characters are in a string using the built-in len() function. This includes letters, digits, spaces, and symbols.
text = "Python"
print(len(text)) # 6
6
Before working with strings, you might want to validate them:
isalpha() – checks if all characters are alphabetsisdigit() – checks if all characters are digitsisalnum() – checks if all characters are alphanumericisspace() – checks for only whitespaceval = "123abc"
print(val.isalnum()) # True
print(val.isdigit()) # False
True
False
Connect what you noticed in the example with the idea below.
A string is an immutable sequence of characters. Indexing selects a character; an operation that changes text returns a new string.
Concatenating text modifies the original string object.
This is the misconception to avoid.Reaching the recap and completing the quizzes are separate milestones.