Introduction
Strings are one of the most commonly used data types in Python programming.
A string is a sequence of characters enclosed within single quotes, double quotes, or triple quotes. Python provides powerful built-in features that allow developers to create, manipulate, search, format, and process string data efficiently.
For example, if you want to store a person’s name, a company name, or a greeting message, you would use a string variable.
What are Python Strings?
A string is a sequence of characters enclosed in quotes.
Strings can contain:
- Letters
- Numbers
- Symbols
- Spaces
- Special characters
Example:
name = "John"
Here:
- name is a variable.
- “John” is a string
Note: Python treats everything inside the quotation marks as text.
Creating Strings in Python
Python provides multiple ways to create strings.
1. Using Double Quotes
Example:
name = "Python"
Output:
2. Using Single Quotes
Example:
language = 'Python'
Output:
3. Using Triple Quotes
Triple quotes are used for multi-line strings.
message = """
Welcome
to
Python
"""
Output:
to
Python
Checking String Type
Use the type() function.
Example:
name = "Python"
print(type(name))
Output:
The str data type represents strings in Python.
Accessing String Characters
Each character in a string has an index.
Example:
text = "Python"
print(text[0])
Output:
Access More Characters:
text = "Python"
print(text[1])
print(text[2])
Output:
t
Indexing starts from 0.
Negative Indexing
Python also supports negative indexing.
Example:
text = "Python"
print(text[-1])
Output:
Negative indexing starts from the end of the string.
String Length
The len() function returns the number of characters in a string.
Example:
text = "Python"
print(len(text))
Output:
Spaces are also counted as characters.
String Slicing
Slicing extracts a portion of a string.
Syntax:
string[start:end]
Example:
text = "Python"
print(text[0:3])
Output:
Another Example:
text = "Python"
print(text[2:6])
Output:
String Concatenation
Concatenation means joining strings together.
Example:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)
Output:
String Repetition
The * operator repeats a string.
Example:
print("Python " * 3)
Output:
Membership Operators
Check whether a substring exists in a string.
Example:
text = "Python Programming"
print("Python" in text)
Output:
Example:
text = "Python Programming"
print("java" in text)
Output:
String Methods
Python provides many useful string methods.
upper()
Converts text to uppercase.
Example:
text = "python"
print(text.upper())
Output:
lower()
Converts text to lowercase.
Example:
text = "PYTHON"
print(text.lower())
Output:
capitalize()
Capitalizes the first character.
Example:
text = "python"
print(text.capitalize())
Output:
title()
Converts the first letter of each word to uppercase.
Example:
text = "python programming"
print(text.title())
Output:
strip()
Removes extra spaces.
Example:
text = " Python "
print(text.strip())
Output:
replace()
Replaces part of a string.
Example:
text = "Hello World"
print(text.replace("World", "Python"))
Output:
split()
Splits a string into a list.
Example:
text = "Python Java C++"
print(text.split())
Output:
join()
Joins elements into a string.
Example:
languages = ["Python", "Java", "C++"]
print(", ".join(languages))
Output:
find()
Returns the position of a substring.
Example:
text = "Python Programming"
print(text.find("Programming"))
Output:
startswith()
Checks whether a string starts with specific text.
Example:
text = "Python Programming"
print(text.startswith("Python"))
Output:
endswith()
Checks whether a string ends with specific text.
Example:
text = "Python Programming"
print(text.endswith("Programming"))
Output:
String Formatting
String formatting allows variables to be inserted into strings.
Using f-Strings
Example:
name = "John"
age = 25
print(f"My name is {name} and I am {age} years old.")
Output:
Using format()
Example:
name = "John"
print("Welcome {}".format(name))
Output:
Escape Characters
Escape characters allow special characters inside strings.
| Escape Character | Description |
|---|---|
| \n | New Line |
| \t | Tab |
| ‘ | Single Quote |
| “ | Double Quote |
| \ | Backslash |
Example:
print("Hello\nPython")
Output:
Python
Looping Through a String
Strings can be traversed using loops.
Example:
text = "Python"
for character in text:
print(character)
Output:
y
t
h
o
n
Real-Life Example
Suppose you are creating a user registration system.
Example:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)
Output:
Here, strings store user information and display it in a readable format.
Email Validation Example
Example:
email = "john@example.com"
print("@" in email)
Output:
This is a simple real-world use of string operations.
Advantages of Python Strings
1. Easy Text Processing
Strings simplify text manipulation.
2. Rich Built-in Methods
Python provides many string functions.
3. Unicode Support
Strings support multiple languages.
4. Flexible Formatting
Easy insertion of variables into text.
5. Efficient Data Handling
Ideal for processing user input and text files.
Common Mistakes
1. Forgetting Quotes
Incorrect:
name = Python
Output:
Correct:
name = "Python"
2. Using Invalid Indexes
Incorrect:
text = "Python"
print(text[10])
Output:
3. Modifying String Characters Directly
Incorrect:
text = "Python"
text[0] = "J"
Output:
Strings are immutable.
4. Confusing Numbers and Strings
Incorrect:
age = "25"
print(age + 5)
Output:
Correct:
age = int(age)
print(age + 5)
5. Ignoring Case Sensitivity
Example:
print("Python" == "python")
Output:
Strings are case-sensitive.
Conclusion
Python strings are one of the most important and frequently used data types in programming. They allow developers to store, process, manipulate, and display textual information efficiently. Python provides powerful string features such as indexing, slicing, concatenation, formatting, and numerous built-in methods that make text processing simple and effective.
Python String – Interview Questions
Q 1: What is a string in Python?
Q 2: How do you create a string?
Q 3: Are strings mutable in Python?
Q 4: How do you access string characters?
Q 5: Can strings be concatenated?
Python String – Objective Questions (MCQs)
Q1. Which of the following is the correct way to create a string in Python?
Q2. What will be the output of the following code?
x = "Python"
print(x[0])
Q3. Which of the following operators is used to concatenate two strings in Python?
Q4. What will be the output of the following code?
x = "Hello World"
print(x.lower())
Q5. Which of the following statements about strings in Python is true?