π¬ Strings in Python#
Strings are the heart of working with text in Python. Whether you want to print a greeting, store a userβs name, or process sentences, strings make it possible! Letβs explore how strings work and the magic you can do with them. β¨
What is a String? π§©#
A string is simply textβthat can be letters, numbers, symbolsβinside quotes.
greeting = "Hello, World!"
- You can use single (’ ‘) or double (" “) quotes.
Creating Strings βοΈ#
name = "Amit"
sentence = 'Python is fun!'
String Operations π²#
1. Concatenation (Joining Strings)#
You can join (concatenate) strings using the + operator.
first = "Good"
second = "Morning"
message = first + " " + second
print(message) # Good Morning
2. Repetition#
Use * to repeat a string.
echo = "Hi! " * 3
print(echo) # Hi! Hi! Hi!
String Indexing & Slicing πͺ#
You can access individual characters or parts (slices) of a string.
text = "Python"
print(text[0]) # 'P' (first character)
print(text[-1]) # 'n' (last character)
print(text[1:4]) # 'yth' (characters 1 to 3)
Useful String Methods π οΈ#
- .upper() β Convert to uppercase
- .lower() β Convert to lowercase
- .title() β Capitalize each word
- .strip() β Remove spaces from start/end
- .replace(old, new) β Replace old with new text
- .find(substring) β Find position of substring
greet = " hello there! "
print(greet.strip()) # "hello there!"
print(greet.upper()) # " HELLO THERE! "
print("apple".replace('a', 'A')) # "Apple"
print("Python".find('th')) # 2
Formatted Strings (f-strings) πͺ#
Make strings with variables easy to read using f-strings.
name = "Sara"
age = 20
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Sara and I am 20 years old.
Practice Questions with Solutions π#
- Practice: Join and print “Good” and “Evening”.
- Solution:
print("Good" + " " + "Evening")
- Practice: How do you print the first and last letter of “Python”?
- Solution:
text = "Python"
print(text, text[-1]) # P n
- Practice: Change “python” to “PYTHON”.
- Solution:
print("python".upper())
Step-by-Step Mini Project: Greeting Builder π#
Task:
Ask the user for their name and create a personalized greeting such as Hello, Priya! Welcome to Python.
Solution:
name = input("Enter your name: ")
greeting = f"Hello, {name}! Welcome to Python."
print(greeting)
Checklist for This Chapter β #
- Created and joined strings
- Indexing and slicing text
- Used useful string methods
- Built f-strings for formatted output
Awesome! Youβre now skilled at handling text with Python strings. Try out message creators, name extractors, or emoji repeaters! π₯³