Strings in Python

A string is a sequence of characters. In Python, strings are immutable and can be created with single, double, or triple quotes.

Creating Strings

# Single quotes
name = 'Alice'
print(name)

# Double quotes
greeting = "Hello"
print(greeting)

# Triple quotes for multi-line strings
message = '''This is
a multi-line
string.'''
print(message)
Alice
Hello
This is
a multi-line
string.

Exercise: Create a string with your name and another string with your favorite hobby, then print them together.

name = "Alice"
hobby = "painting"
print(name + " enjoys " + hobby)
Alice enjoys painting

String Length

text = "Hello"
print(len(text))

Accessing Characters (Indexing & Slicing)

word = "Python"
print(word[0])    # First character
print(word[-1])   # Last character
print(word[0:3])  # Slice from index 0 to 2

Exercise: Print the first three letters of your name using slicing.

name = "Alice"
print(name[:3])
Ali

String Operations

first = "Hello"
second = "World"
print(first + " " + second)  # Concatenation
laugh = "ha"
print(laugh * 3)              # Repetition

Exercise: Concatenate your first and last name with a space between them.

first_name = "Alice"
last_name = "Smith"
full_name = first_name + " " + last_name
print(full_name)
Alice Smith

String Methods

s = "  Hello World  "
print(s.lower())
print(s.upper())
print(s.title())
print(s.strip())
print(s.replace("World", "Python"))
print(s.split())
print("-".join(["a", "b", "c"]))

Exercise: Take a sentence and:

  1. Convert it to uppercase.
  2. Replace one word with another.
  3. Split it into a list of words.
sentence = "Python is fun"
print(sentence.upper())
print(sentence.replace("fun", "awesome"))
print(sentence.split())
PYTHON IS FUN
Python is awesome
['Python', 'is', 'fun']

Escape Characters

print("Line 1\nLine 2")
print("Tab\tSpace")
print("She said \"Hello\"")

f-Strings (Formatted Strings)

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

Exercise: Create two variables (city and temperature) and print a sentence using f-strings.

city = "Tokyo"
temperature = 26
print(f"The temperature in {city} is {temperature}°C today.")
The temperature in Tokyo is 26°C today.

Strings are Immutable

word = "Python"
# word[0] = "J"  # This would cause an error
word = "J" + word[1:]
print(word)

Summary

  • Strings store sequences of characters.
  • They are immutable.
  • You can use indexing, slicing, concatenation, and repetition.
  • String methods allow transformations and queries.
  • f-strings provide an easy way to format text.