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 quotesname ='Alice'print(name)# Double quotesgreeting ="Hello"print(greeting)# Triple quotes for multi-line stringsmessage ='''This isa multi-linestring.'''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 characterprint(word[-1]) # Last characterprint(word[0:3]) # Slice from index 0 to 2
Exercise: Print the first three letters of your name using slicing.
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:
Convert it to uppercase.
Replace one word with another.
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 =25print(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 =26print(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 errorword ="J"+ word[1:]print(word)
Summary
Strings store sequences of characters.
They are immutable.
You can use indexing, slicing, concatenation, and repetition.