STRINGS
Strings are one of the most important data types in Python. We use strings whenever we work with names, messages, filenames, database errors, log files, user input, and other text data.
In this tutorial, we will learn Python strings from the absolute basics with simple examples.
Table of Contents
- What is a String?
- Creating Strings
- Finding String Length with len()
- Python Functions vs String Methods
- upper() and lower()
- Removing Spaces with strip()
- Replacing Text with replace()
- String Immutability
- String Indexing
- Negative Indexing
- String Slicing
- Slicing Shortcuts
- Slicing with Step
- Reversing a String
- in and not in
- startswith() and endswith()
- split()
- join()
- find()
- count()
- F-Strings
- Common Beginner Mistakes
- Quick Revision
- Practice Questions
1. What is a String?
A string is text stored in Python.
Examples:
name = "Prabhu"
city = "Hyderabad"
job = "DBA"
In Python, the string data type is called:
str
2. Creating Strings
Strings can be created using quotes.
name = "Prabhu"
print(name)
print(type(name))
Output:
Prabhu
<class 'str'>
3. Finding String Length with len()
The len() function returns the number of characters
in a string.
name = "Prabhu"
print(len(name))
Output:
6
Spaces are also counted as characters.
name = "Prabhu Charan"
print(len(name))
Output:
13
4. Python Functions vs String Methods
Beginners often get confused because both functions and methods use parentheses.
Function
len(name)
The general pattern is:
function(value)
Method
name.upper()
The general pattern is:
object.method()
len(name) → Functionname.upper() → Method
5. upper() and lower()
upper() converts text to uppercase.
lower() converts text to lowercase.
city = "Hyderabad"
print(city.upper())
print(city.lower())
Output:
HYDERABAD
hyderabad
6. Removing Extra Spaces with strip()
strip() removes spaces from the beginning and end
of a string.
name = " Prabhu "
print(name.strip())
Output:
Prabhu
This is especially useful with user input.
name = input("Enter your name: ")
name = name.strip()
print(f"Hello {name}")
7. Replacing Text with replace()
The replace() method replaces one part of a string
with another.
text = "I like Java"
text = text.replace("Java", "Python")
print(text)
Output:
I like Python
8. Strings are Immutable
One very important Python concept is that strings are immutable.
This means string methods normally create a new string rather than modifying the original string directly.
name = "prabhu"
name.upper()
print(name)
Output:
prabhu
The result was created, but we did not save it.
To save the new value:
name = "prabhu"
name = name.upper()
print(name)
Output:
PRABHU
name.upper() → result created but not savedname = name.upper() → result created and saved
9. String Indexing
Each character in a Python string has an index position.
Python indexing starts from 0.
Character: P y t h o n
Index: 0 1 2 3 4 5
Example:
name = "Python"
print(name[0])
print(name[1])
print(name[2])
Output:
P
y
t
10. Negative Indexing
Python can also count backwards from the end of a string.
Character: P y t h o n
Positive Index: 0 1 2 3 4 5
Negative Index: -6 -5 -4 -3 -2 -1
Example:
name = "Python"
print(name[-1])
print(name[-2])
Output:
n
o
11. String Slicing
Slicing allows us to extract multiple characters from a string.
The syntax is:
string[start:stop]
The start position is included, but the stop position is excluded.
text = "Database"
print(text[0:4])
Output:
Data
text[0:4] takes indexes:
0, 1, 2, 3
Index 4 is not included.
12. Slicing Shortcuts
text = "Database"
print(text[:4])
print(text[4:])
print(text[:])
Output:
Data
base
Database
Remember:
text[:4] → beginning to before index 4
text[4:] → index 4 to the end
text[:] → entire string
13. Slicing with Step
The full slicing syntax is:
string[start:stop:step]
Example:
text = "Database"
print(text[::2])
print(text[1::2])
Output:
Dtbs
aaae
14. Reversing a String
We can reverse a string using a step value of -1.
text = "Python"
print(text[::-1])
Output:
nohtyP
15. Checking Text with in and not in
The in operator checks whether something exists
inside a string.
text = "PostgreSQL Database"
print("SQL" in text)
print("Oracle" in text)
Output:
True
False
not in checks whether something is absent.
print("Oracle" not in text)
Output:
True
"Python" and "python" are different.
16. startswith() and endswith()
startswith() checks the beginning of a string.
endswith() checks the end.
filename = "backup.sql"
print(filename.startswith("backup"))
print(filename.endswith(".sql"))
print(filename.endswith(".csv"))
Output:
True
True
False
Practical Example
filename = input("Enter file name: ")
if filename.endswith(".csv"):
print("CSV file")
else:
print("Not a CSV file")
17. Splitting Strings with split()
split() breaks one string into multiple pieces.
text = "apple,banana,mango"
result = text.split(",")
print(result)
Output:
['apple', 'banana', 'mango']
The result of split() is a Python list.
Another example:
data = "Prabhu|DBA|Hyderabad"
result = data.split("|")
print(result)
Output:
['Prabhu', 'DBA', 'Hyderabad']
18. Joining Strings with join()
join() performs the opposite operation of
split().
words = ["Python", "is", "easy"]
result = " ".join(words)
print(result)
Output:
Python is easy
Different separators can be used:
print("-".join(words))
print(",".join(words))
Output:
Python-is-easy
Python,is,easy
split() → one string becomes many piecesjoin() → many string pieces become one string
19. Finding Text with find()
find() returns the index where some text starts.
text = "Python is easy"
print(text.find("easy"))
Output:
10
If the value cannot be found, find() returns
-1.
print(text.find("Java"))
Output:
-1
20. Counting Occurrences with count()
count() tells us how many times something appears.
text = "banana"
print(text.count("a"))
Output:
3
Remember the difference:
find() → WHERE does it start?
count() → HOW MANY times does it occur?
21. F-Strings
F-strings are one of the cleanest ways to combine text and variables.
name = "Prabhu"
experience = 10
print(f"My name is {name}")
print(f"I have {experience} years of experience")
Output:
My name is Prabhu
I have 10 years of experience
Python can also evaluate expressions inside an f-string.
experience = 10
print(f"Next year I will have {experience + 1} years of experience")
Output:
Next year I will have 11 years of experience
22. Common Beginner Mistakes
Mistake 1: Forgetting that indexing starts from 0
text = "Python"
print(text[0])
Output is P, because the first index is 0.
Mistake 2: Including the stop index in slicing
text[0:3]
This uses indexes:
0, 1, 2
Index 3 is excluded.
Mistake 3: Forgetting to save a changed string
name.upper()
This does not permanently change name.
Use:
name = name.upper()
Mistake 4: Forgetting case sensitivity
"Python" != "python"
Mistake 5: Confusing find() and count()
find() → position
count() → number of occurrences
23. Quick Revision
| Operation | Purpose |
|---|---|
len(text) |
Number of characters |
text.upper() |
Uppercase |
text.lower() |
Lowercase |
text.strip() |
Remove outside spaces |
text.replace() |
Replace text |
text[0] |
First character |
text[-1] |
Last character |
text[0:4] |
Slice text |
text[::-1] |
Reverse string |
"SQL" in text |
Check presence |
text.startswith() |
Check beginning |
text.endswith() |
Check ending |
text.split() |
String to pieces |
" ".join(words) |
Pieces to string |
text.find() |
Find starting index |
text.count() |
Count occurrences |
f"{name}" |
Insert variable into text |
24. Practice Questions
Try these exercises without looking at the answers first.
Exercise 1
text = "Python"
print(text[0])
print(text[-1])
print(text[::-1])
Exercise 2
text = "Database"
print(text[:4])
print(text[4:])
Exercise 3
filename = "backup.sql"
print(filename.endswith(".sql"))
print(filename.startswith("backup"))
Exercise 4
data = "PostgreSQL|MySQL|Redshift"
result = data.split("|")
print(result)
Exercise 5
text = "database database python"
print(text.count("database"))
print(text.find("python"))
Conclusion
Python strings are extremely important because almost every real-world Python application works with text in some form.
In this tutorial we learned how to create strings, change case, remove spaces, replace text, access characters, perform slicing, search strings, split and join text, count values, and use f-strings.
The next topic in our Python learning roadmap is:
Python Lists
Lists allow us to store multiple values inside a single variable.
Comments
Post a Comment