Lesson 8: Strings and String Methods

๐ŸŽฏ Lesson Objective

To understand how to work with text data in Python, perform string operations, and use built-in string methods for manipulation and analysis.


๐Ÿง  1. What Is a String?

A string is a sequence of characters enclosed in single quotes (”), double quotes (“”), or triple quotes (”’ ”’).

โœ… Example:

name = "Sameer"
greeting = 'Hello!'
message = '''Welcome to Python programming.'''

โš™๏ธ 2. Accessing String Characters

Strings are indexed, meaning each character has a position (starting from 0).

text = "Python"
print(text[0])   # First character
print(text[5])   # Last character

Output:

P
n

๐Ÿ”„ 3. String Slicing

You can extract parts of a string using slicing.

word = "Programming"
print(word[0:6])     # Output: Progra
print(word[3:])      # Output: gramming
print(word[:5])      # Output: Progr
print(word[-3:])     # Output: ing

๐Ÿงฉ 4. String Concatenation and Repetition

You can join strings using + and repeat using *.

a = "Hello"
b = "Python"
print(a + " " + b)   # Concatenation
print(a * 3)         # Repetition

Output:

Hello Python
HelloHelloHello

๐Ÿ”ข 5. String Length

Find the number of characters using len().

text = "Python"
print(len(text))

Output:

6

โœ‚๏ธ 6. Checking for Substrings

You can check if a substring exists using the in or not in operator.

text = "Learning Python"
print("Python" in text)
print("Java" not in text)

Output:

True
True

๐Ÿงฐ 7. Common String Methods

MethodDescriptionExample
upper()Converts all characters to uppercase"hello".upper() โ†’ HELLO
lower()Converts all characters to lowercase"HELLO".lower() โ†’ hello
title()Capitalizes first letter of each word"hello world".title() โ†’ Hello World
strip()Removes spaces from start and end" hello ".strip() โ†’ hello
replace()Replaces substring"I love Java".replace("Java", "Python") โ†’ I love Python
split()Splits string into list"a,b,c".split(",") โ†’ ['a', 'b', 'c']
join()Joins list into a string"-".join(['a','b','c']) โ†’ a-b-c
find()Returns index of substring"python".find("th") โ†’ 2
count()Counts occurrences"apple".count("p") โ†’ 2
startswith() / endswith()Checks prefix/suffix"Python".startswith("Py") โ†’ True

๐Ÿ”ค 8. Escape Characters

Used to include special characters inside strings.

Escape CodeMeaningExample
\'Single quote'It\'s fun'
\"Double quote"He said \"Hi\""
\\Backslash"C:\\Users"
\nNew line"Hello\nWorld"
\tTab space"Hello\tWorld"

โœ… Example:

print("Name:\tSameer\nCity:\tWarangal")

Output:

Name:   Sameer
City:   Warangal

๐Ÿงฎ 9. String Formatting

You can use f-strings or format() for neat output.

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

Output:

My name is Sameer and I am 25 years old.

๐ŸŒ 10. Real-Life Example: Text Analyzer

text = input("Enter a sentence: ")
print("Total characters:", len(text))
print("Uppercase:", text.upper())
print("Number of spaces:", text.count(" "))
print("Reversed:", text[::-1])

Output (for input โ€œPython is funโ€):

Total characters: 13
Uppercase: PYTHON IS FUN
Number of spaces: 2
Reversed: nuf si nohtyP

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *