Strings are one of the most important and widely used data types in Python. Almost every Python program works with text, whether it is displaying messages, storing names, processing user input, reading files, or manipulating data. Understanding strings is essential because they are used in web development, automation, data processing, game development, and many other programming tasks.
A string is a sequence of characters enclosed within quotation marks. These characters can include letters, numbers, symbols, spaces, and even special characters. Python treats every string as an object and provides numerous built-in functions and methods to make working with text simple and efficient.
Unlike some programming languages, Python makes string handling straightforward. You can create strings using single quotes, double quotes, or triple quotes, depending on your needs. Python also supports multi-line strings and Unicode characters, making it suitable for working with text in different languages.
In this lesson, you will learn how to create strings, access individual characters, measure string length, and understand the different ways Python represents text. Later lessons will cover indexing, slicing, string methods, and advanced string operations in greater detail.
After completing this lesson, you will be able to:
len() function.A string is a sequence of one or more characters enclosed within quotation marks. Characters may include letters, digits, punctuation marks, spaces, and special symbols.
In Python, strings are represented by the str data type.
name = "Rahul"
city = "Delhi"
message = "Welcome to Python"
print(name)
print(city)
print(message)
Output
Rahul
Delhi
Welcome to Python
You can verify that a value is a string by using the type() function.
text = "Python"
print(type(text))
Output
<class 'str'>
Python allows you to create strings using different types of quotation marks. All of them create the same str object.
language = 'Python'
print(language)
Output
Python
language = "Python"
print(language)
Output
Python
Triple quotes are useful when creating long strings or multi-line text.
message = """Welcome
to
Python"""
print(message)
Output
Welcome
to
Python
Single and double quotes work in the same way. You can choose either style according to your preference or coding standards.
| Single Quotes | Double Quotes |
|---|---|
'Python' |
"Python" |
'Hello' |
"Hello" |
Double quotes are often used when the text contains an apostrophe.
message = "Python is easy."
print(message)
Triple quotes allow you to write text on multiple lines without using special characters.
paragraph = """Python is easy to learn.
It is powerful.
It is widely used."""
print(paragraph)
Output
Python is easy to learn.
It is powerful.
It is widely used.
Each character in a string has a position called an index. Python starts counting from 0.
language = "Python"
print(language[0])
print(language[1])
print(language[2])
Output
P
y
t
Every character has its own index.
| Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
String indexing will be explained in detail in the next lesson.
You can determine the number of characters in a string using the len() function.
language = "Python"
print(len(language))
Output
6
Spaces are also counted as characters.
text = "Hello World"
print(len(text))
Output
11
In this section, you learned what a Python string is and why it is one of the most important data types in programming. You explored different ways to create strings using single, double, and triple quotes, created multi-line strings, accessed individual characters using indexes, and used the len() function to determine the length of a string. In the next section, you will learn how string indexing and slicing work, how to access specific portions of a string, and how to loop through strings efficiently.
Once you know how to create strings, the next step is learning how to access specific characters or portions of a string. Python provides powerful features such as indexing and slicing that allow you to retrieve characters or substrings efficiently.
Since a string is a sequence of characters, every character has a unique position known as an index.
Python uses zero-based indexing, which means the first character starts at index 0.
language = "Python"
print(language[0])
print(language[1])
print(language[2])
print(language[3])
print(language[4])
print(language[5])
Output
P
y
t
h
o
n
| Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
If you try to access an index that does not exist, Python raises an IndexError.
language = "Python"
print(language[10])
Output
IndexError: string index out of range
Python also supports negative indexing, allowing you to access characters from the end of the string.
| Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Negative Index | -6 | -5 | -4 | -3 | -2 | -1 |
language = "Python"
print(language[-1])
print(language[-2])
print(language[-3])
Output
n
o
h
Negative indexing is useful when you want to access characters from the end without knowing the string length.
Slicing allows you to extract a portion of a string instead of a single character.
string[start:stop]
The start index is included, while the stop index is excluded.
language = "Python"
print(language[0:2])
print(language[2:5])
print(language[1:4])
Output
Py
tho
yth
You can omit the start or stop index to make slicing more flexible.
language = "Python"
print(language[:4])
print(language[2:])
Output
Pyth
thon
The optional step value lets you skip characters while slicing.
string[start:stop:step]
language = "Python"
print(language[0:6:2])
Output
Pto
You can reverse a string using a negative step.
language = "Python"
print(language[::-1])
Output
nohtyP
Since strings are sequences, you can iterate through each character using a for loop.
language = "Python"
for letter in language:
print(letter)
Output
P
y
t
h
o
n
The in and not in operators are used to check whether a substring exists inside a string.
language = "Python Programming"
print("Python" in language)
print("Java" in language)
print("Java" not in language)
Output
True
False
True
In this section, you learned how to access characters using positive and negative indexing, extract parts of a string through slicing, reverse strings using step values, loop through individual characters, and check whether text exists within a string using the in and not in operators. These techniques are fundamental for working with text in Python. In the next section, you will explore Python’s built-in string methods such as upper(), lower(), replace(), split(), and many others that simplify string manipulation.
Python provides a rich collection of built-in string methods that make it easy to modify, search, split, and format text. These methods do not change the original string because strings are immutable. Instead, they return a new string with the desired changes.
Learning these methods will help you write cleaner and more efficient Python programs.
The upper() method converts all characters in a string to uppercase.
text = "python programming"
print(text.upper())
Output
PYTHON PROGRAMMING
The lower() method converts all characters to lowercase.
text = "PYTHON"
print(text.lower())
Output
python
The strip() method removes spaces from the beginning and end of a string.
text = " Python "
print(text.strip())
Output
Python
The replace() method replaces one part of a string with another.
text = "I like Java"
print(text.replace("Java", "Python"))
Output
I like Python
The split() method divides a string into a list.
text = "Apple Banana Mango"
print(text.split())
Output
['Apple', 'Banana', 'Mango']
The join() method joins elements of a list into a single string.
fruits = ["Apple", "Banana", "Mango"]
print(", ".join(fruits))
Output
Apple, Banana, Mango
The find() method returns the position of the first occurrence of a substring.
text = "Python Programming"
print(text.find("Programming"))
Output
7
If the text is not found, the method returns -1.
The count() method counts how many times a substring appears.
text = "banana"
print(text.count("a"))
Output
3
The startswith() method checks whether a string starts with a specified value.
text = "Python Programming"
print(text.startswith("Python"))
Output
True
The endswith() method checks whether a string ends with a specified value.
text = "document.pdf"
print(text.endswith(".pdf"))
Output
True
String formatting allows you to insert variables into a string, making output more readable and dynamic.
format() Methodname = "Rahul"
age = 22
print("My name is {} and I am {} years old.".format(name, age))
Output
My name is Rahul and I am 22 years old.
Introduced in Python 3.6, f-strings provide a simple and efficient way to format strings.
name = "Rahul"
marks = 95
print(f"{name} scored {marks} marks.")
Output
Rahul scored 95 marks.
f-strings are generally preferred because they are easier to read and write.
+ repeatedly instead of string formatting for long text.strip() to remove unwanted spaces from user input.In this section, you learned how to use Python’s most common string methods to manipulate and format text. You explored methods such as upper(), lower(), strip(), replace(), split(), join(), find(), count(), startswith(), and endswith(). You also learned how to format strings using the format() method and modern f-strings. In the final section, you will review the lesson with a summary, key takeaways, FAQs, coding exercises, interview questions, and a mini project.
In this lesson, you learned the fundamentals of Python strings, one of the most commonly used data types in programming. You explored how to create strings using single, double, and triple quotes, access characters through indexing, extract text using slicing, and iterate through strings using loops.
You also learned how to manipulate strings with Python’s built-in methods, including converting text to uppercase or lowercase, removing extra spaces, replacing text, splitting and joining strings, searching for substrings, and formatting output using both the format() method and f-strings.
With these concepts, you now have a solid foundation for working with text in Python programs.
str data type.A string is a sequence of characters enclosed within quotation marks.
The str data type represents strings in Python.
Yes. Both create string objects and work in the same way.
Indexing allows you to access individual characters using their position.
Slicing extracts a portion of a string using the start:stop:step syntax.
No. Strings are immutable, which means they cannot be modified after creation.
The upper() method converts all characters to uppercase.
Using f-strings is the recommended approach because they are simple, readable, and efficient.
"Learn Python Programming".replace() method.a appears in a string.format() method and f-strings?Create a Python program that stores and displays student information using string operations.
Your program should:
Congratulations! You have learned how to create, access, manipulate, and format strings in Python. Strings are used in almost every Python program, making this one of the most important topics for beginners.
In the next lesson, you will learn String Indexing & Slicing in greater depth. You will explore advanced slicing techniques, negative indexing, step values, reversing strings, and practical examples for extracting text efficiently.