🐍 STRINGS AND STRING FUNCTIONS IN PYTHON
Creating, Accessing, Manipulating and Processing Strings
📘 1. What is a String?
A string is a sequence of characters enclosed
within single quotes, double quotes, or triple quotes.
Strings can contain: letters, numbers, spaces, symbols and special characters.
Strings can contain: letters, numbers, spaces, symbols and special characters.
name = "Python"
college = 'Computer Science'
message = """Welcome to Python Programming"""
🔤 2. Creating Strings
str1 = 'Hello'
str2 = "Python"
str3 = '''Programming'''
str4 = """Computer Science"""
Hello
Python
Programming
Computer Science
Python
Programming
Computer Science
3️⃣ Single and Double Quotes
a = 'Hello'
b = "World"
print(a)
print(b)
Hello
World
World
💡 Single quotes and double quotes can both be used to create strings.
4️⃣ Triple-Quoted Strings
Triple quotes are commonly used for multiline strings.
message = """Python
is
easy to learn."""
print(message)
Python
is
easy to learn.
is
easy to learn.
🔒 5. Strings are Immutable
Strings in Python are immutable. This means that
individual characters of an existing string cannot be changed directly.
text = "Python"
# text[0] = "J" # Error
⚠️ A new string must be created if the value needs to be changed.
text = "Python"
text = "J" + text[1:]
print(text)
Jython
6️⃣ String Indexing
Each character has an index position.
text = "PYTHON"
print(text[0])
print(text[1])
print(text[5])
P
Y
N
Y
N
| Character | P | Y | T | H | O | N |
|---|---|---|---|---|---|---|
| Positive Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative Index | -6 | -5 | -4 | -3 | -2 | -1 |
7️⃣ String Slicing
text = "PYTHON"
print(text[0:3])
print(text[2:6])
print(text[:4])
print(text[2:])
PYT
THON
PYTH
THON
THON
PYTH
THON
Syntax:
string[start : stop : step]
8️⃣ String Concatenation
The + operator joins two or more strings.
first = "Hello"
second = "Python"
result = first + " " + second
print(result)
Hello Python
9️⃣ String Repetition
The * operator can repeat a string.
print("Python " * 3)
Python Python Python
🔢 10. len() Function
The len() function returns the number of characters in a string.
text = "Python"
print(len(text))
6
🛠️ 11. Important String Functions and Methods
len()
Returns string length.
Returns string length.
lower()
Converts characters to lowercase.
Converts characters to lowercase.
upper()
Converts characters to uppercase.
Converts characters to uppercase.
capitalize()
Capitalizes the first character.
Capitalizes the first character.
title()
Capitalizes the first character of each word.
Capitalizes the first character of each word.
swapcase()
Swaps uppercase and lowercase characters.
Swaps uppercase and lowercase characters.
strip()
Removes leading and trailing whitespace.
Removes leading and trailing whitespace.
replace()
Replaces part of a string.
Replaces part of a string.
split()
Splits a string into a list.
Splits a string into a list.
join()
Joins elements into a string.
Joins elements into a string.
find()
Finds the position of a substring.
Finds the position of a substring.
count()
Counts occurrences.
Counts occurrences.
startswith()
Checks the beginning of a string.
Checks the beginning of a string.
endswith()
Checks the ending of a string.
Checks the ending of a string.
isdigit()
Checks whether all characters are digits.
Checks whether all characters are digits.
isalpha()
Checks whether all characters are alphabetic.
Checks whether all characters are alphabetic.
1️⃣2️⃣ lower()
text = "PYTHON"
print(text.lower())
python
1️⃣3️⃣ upper()
text = "python"
print(text.upper())
PYTHON
1️⃣4️⃣ capitalize()
text = "python programming"
print(text.capitalize())
Python programming
1️⃣5️⃣ title()
text = "python programming language"
print(text.title())
Python Programming Language
1️⃣6️⃣ swapcase()
text = "Python"
print(text.swapcase())
pYTHON
1️⃣7️⃣ strip()
text = " Python "
print(text.strip())
Python
1️⃣8️⃣ replace()
text = "I like Java"
print(text.replace("Java", "Python"))
I like Python
1️⃣9️⃣ find()
text = "Python Programming"
print(text.find("Program"))
7
The returned value is the starting index of the searched substring.
If the substring is not found, find() returns -1.
2️⃣0️⃣ count()
text = "banana"
print(text.count("a"))
3
2️⃣1️⃣ split()
text = "Python is easy"
words = text.split()
print(words)
['Python', 'is', 'easy']
2️⃣2️⃣ join()
words = ["Python", "is", "easy"]
result = " ".join(words)
print(result)
Python is easy
2️⃣3️⃣ startswith() and endswith()
text = "Python Programming"
print(text.startswith("Python"))
print(text.endswith("Programming"))
True
True
True
2️⃣4️⃣ isalpha()
text = "Python"
print(text.isalpha())
True
2️⃣5️⃣ isdigit()
text = "12345"
print(text.isdigit())
True
🎨 2️⃣6️⃣ String Formatting
String formatting allows values to be inserted into strings.
name = "Bijan"
age = 25
print(f"My name is {name} and I am {age} years old.")
My name is Bijan and I am 25 years old.
💡 f-string is a convenient way to insert variables
inside a string using
{ }.
🔐 2️⃣7️⃣ Escape Characters
| Escape Character | Meaning |
|---|---|
\n |
New line |
\t |
Tab |
\\ |
Backslash |
\' |
Single quote |
\" |
Double quote |
print("Hello\nPython")
print("Name\tAge")
Hello
Python
Name Age
Python
Name Age
⚖️ 2️⃣8️⃣ String Comparison
a = "apple"
b = "banana"
print(a == b)
print(a != b)
False
True
True
Strings can be compared using operators such as
==, !=, <, >,
<= and >=.
🔍 2️⃣9️⃣ Membership Operators
text = "Python Programming"
print("Python" in text)
print("Java" not in text)
True
True
True
🎮 3️⃣0️⃣ Interactive String Demonstration
Click a button to see a common string operation.
Result will appear here...
✅ Advantages of Strings in Python
- Easy to create and manipulate.
- Large number of built-in methods are available.
- Supports indexing and slicing.
- Supports Unicode characters.
- Useful for text processing.
- Can be combined using concatenation.
- Useful in web development, data processing and file handling.
- Immutable nature makes strings predictable and safe to use.
❌ Limitations of Strings
- Individual characters cannot be changed directly.
- Repeated string modification may create new string objects.
- Very large text processing may require efficient techniques.
- Incorrect indexing can produce an IndexError.
📋 Important String Functions / Methods at a Glance
| Function / Method | Purpose | Example |
|---|---|---|
| len() | Find length | len("Python") |
| lower() | Lowercase | "PYTHON".lower() |
| upper() | Uppercase | "python".upper() |
| capitalize() | Capitalize first character | "python".capitalize() |
| title() | Title case | "python language".title() |
| strip() | Remove surrounding whitespace | " Python ".strip() |
| replace() | Replace text | "Java".replace("Java","Python") |
| find() | Find substring position | "Python".find("th") |
| count() | Count occurrences | "banana".count("a") |
| split() | Split into list | "A B C".split() |
| join() | Join strings | "-".join(["A","B"]) |
| startswith() | Check beginning | "Python".startswith("Py") |
| endswith() | Check ending | "Python".endswith("on") |
| isalpha() | Check alphabetic characters | "Python".isalpha() |
| isdigit() | Check digits | "123".isdigit() |
🎯 Important Points for Examination
- A string is a sequence of characters.
- Strings can be enclosed in single, double or triple quotes.
- Python strings are immutable.
- String indexing starts from 0.
- Negative indexing starts from -1.
- String slicing uses
[start:stop:step]. len()returns the length of a string.lower()converts a string to lowercase.upper()converts a string to uppercase.split()converts a string into a list.join()joins elements into a string.find()returns the position of a substring.replace()replaces one substring with another.isalpha()checks alphabetic characters.isdigit()checks whether all characters are digits.
📌 Quick Summary
| Concept | Example |
|---|---|
| Create String | "Python" |
| Indexing | "Python"[0] |
| Slicing | "Python"[0:3] |
| Length | len("Python") |
| Uppercase | "python".upper() |
| Lowercase | "PYTHON".lower() |
| Replace | "Java".replace("Java","Python") |
| Split | "A B".split() |
| Join | "-".join(["A","B"]) |
| Find | "Python".find("th") |
No comments:
Post a Comment