Learn Without Walls
← Previous Lesson Lesson 3 of 4 Next Lesson →

Strings Basics

What You'll Learn

1. What is a String?

String (str): A sequence of characters enclosed in quotes. Strings represent text data in Python -- names, messages, addresses, and any other text.

Strings are one of the most common data types in programming. Almost every program works with text in some way, whether it is displaying a message to the user, storing a name, or processing a document.

greeting = "Hello, World!"
name = "Alice"
address = "123 Main Street"
empty = ""    # An empty string (has zero characters)

print(greeting)
print(type(greeting))
Hello, World! <class 'str'>

2. Single Quotes vs. Double Quotes

Python lets you create strings using either single quotes (') or double quotes ("). They work exactly the same way:

message1 = 'Hello, World!'
message2 = "Hello, World!"

print(message1 == message2)  # Are they equal?
True

So when should you use one over the other? The main reason is when your string contains a quote character:

# Use double quotes when your string contains a single quote
sentence = "It's a beautiful day!"
print(sentence)

# Use single quotes when your string contains double quotes
quote = 'She said "hello" to everyone.'
print(quote)
It's a beautiful day! She said "hello" to everyone.
Common Error: If you try 'It's a beautiful day!', Python sees the apostrophe as the end of the string and gets confused by the remaining text. Use double quotes to avoid this problem.

3. Escape Characters

Sometimes you need to include special characters in a string. Python uses the backslash (\) as an escape character to give characters special meaning:

Escape SequenceMeaningExample
\'Single quote'It\'s fun'
\"Double quote"She said \"hi\""
\\Backslash"C:\\Users\\Alice"
\nNew line"Line 1\nLine 2"
\tTab"Name:\tAlice"
# Using escape characters
print("She said \"hello\" to me.")
print('It\'s a great day!')
print("First line\nSecond line")
print("Name:\tAlice")
print("File path: C:\\Users\\Documents")
She said "hello" to me. It's a great day! First line Second line Name: Alice File path: C:\Users\Documents

You can also create multi-line strings using triple quotes:

poem = """Roses are red,
Violets are blue,
Python is awesome,
And so are you!"""

print(poem)
Roses are red, Violets are blue, Python is awesome, And so are you!

4. String Concatenation (+)

You can join strings together using the + operator. This is called concatenation:

first_name = "Alice"
last_name = "Smith"

full_name = first_name + " " + last_name
print(full_name)
Alice Smith
Important: You cannot concatenate a string with a number directly. Python will raise a TypeError.
# This will cause an error!
# age = 25
# message = "I am " + age + " years old"   # TypeError!

# Fix: convert the number to a string first
age = 25
message = "I am " + str(age) + " years old"
print(message)
I am 25 years old

5. String Repetition (*)

You can repeat a string multiple times using the * operator:

line = "-" * 30
print(line)

cheer = "Go! " * 3
print(cheer)

pattern = "*-" * 10
print(pattern)
------------------------------ Go! Go! Go! *-*-*-*-*-*-*-*-*-*-

Practical Use: Creating Formatted Output

title = "Report Card"
border = "=" * 30

print(border)
print(title)
print(border)
============================== Report Card ==============================

6. String Length and Indexing

The len() function tells you how many characters are in a string:

name = "Alice"
print(len(name))      # 5

message = "Hello, World!"
print(len(message))   # 13 (spaces and punctuation count!)

empty = ""
print(len(empty))     # 0
5 13 0

You can access individual characters using indexing. Python uses zero-based indexing, meaning the first character is at position 0:

word = "Python"
#        P  y  t  h  o  n
# Index: 0  1  2  3  4  5

print(word[0])    # P (first character)
print(word[1])    # y (second character)
print(word[5])    # n (last character)
print(word[-1])   # n (last character using negative index)
print(word[-2])   # o (second to last)
P y n n o
Zero-based indexing: In Python (and most programming languages), counting starts at 0, not 1. The first element is at index 0, the second at index 1, and so on.

Check Your Understanding

Question 1: What will len("Hello\nWorld") return?

Answer: 11

The \n escape sequence counts as a single character (a newline), so: H-e-l-l-o-\n-W-o-r-l-d = 11 characters.

Question 2: Given text = "Python", what is text[2]?

Answer: "t"

Index 0 is "P", index 1 is "y", index 2 is "t".

Try It Yourself!

  1. Create a string with your full name. Print it and its length.
  2. Create a string that contains both single and double quotes.
  3. Use + to build a greeting that says "Hello, [your name]! Welcome!"
  4. Print a line of 50 asterisks using * repetition.

Key Takeaways

← Previous: Numbers Next: Booleans →