Python Strings

Let’s look at strings

  1. Notice

    A string is an immutable sequence of characters. Indexing selects a character; an operation that changes text returns a new string.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
name = 'Ada'
first = name[0]
greeting = "Hello, " + name
print(first)
print(greeting)
Live state

Top-level scope

name→Object 1
first→Object 2
greeting→Object 3
Object 1 · str'Ada'Object 2 · str'A'Object 3 · str'Hello, Ada'
This step

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 ordered sequence

Each position identifies one character. The first position is zero.

Image brief

Alt text
The string cat has zero-based positions: c at index 0, a at index 1, and t at index 2.
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python Strings". Teaching focus: Each position identifies one character. The first position is zero. Depict exactly the relationships and labels in this reference diagram: text = "cat" INDEX 0 1 2 +---+ +---+ +---+ CHARACTER | c | | a | | t | +---+ +---+ +---+ text[0] --> "c" Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: The string cat has zero-based positions: c at index 0, a at index 1, and t at index 2.

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
name = 'Ada'
first = name[0]
greeting = "Hello, " + name
print(first)
print(greeting)
Live state

Top-level scope

name→Object 1
first→Object 2
greeting→Object 3
Object 1 · str'Ada'Object 2 · str'A'Object 3 · str'Hello, Ada'
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
A
Hello, Ada

What do you expect this program to print?

What does this example display?

name = 'Ada'
first = name[0]
greeting = "Hello, " + name
print(first)
print(greeting)
What does this example display?
Choose one answer. You can try again.

Answer and explanation

A Hello, Ada

Follow the printed values in order. The output is: A Hello, Ada

Which explanation matches what you learned?

Which explanation matches what you learned?
Choose one answer. You can try again.

Answer and explanation

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.

What is a String in Python?

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.

Creating Strings

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!"'

Multiline Strings

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."""

Accessing Characters in a String

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.

String Slicing

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

Immutability of Strings

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

Common String Methods

Python provides several built-in methods to work with strings:

  • lower(): Converts all characters to lowercase
  • upper(): Converts all characters to uppercase
  • strip(): Removes leading and trailing whitespace
  • replace(old, new): Replaces substring
  • split(): Splits the string into a list
  • join(): Joins elements of a list with a string separator
s = "  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.

String Formatting

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.

Checking Substrings

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

Looping Through a String

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

Length of a String

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

Validation & Checks

Before working with strings, you might want to validate them:

  • isalpha() – checks if all characters are alphabets
  • isdigit() – checks if all characters are digits
  • isalnum() – checks if all characters are alphanumeric
  • isspace() – checks for only whitespace
val = "123abc"
print(val.isalnum())  # True
print(val.isdigit())  # False
True
False

What to remember

Connect what you noticed in the example with the idea below.

Remember

A string is an immutable sequence of characters. Indexing selects a character; an operation that changes text returns a new string.

Watch out for this idea

Concatenating text modifies the original string object.

This is the misconception to avoid.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Python Type Conversions →