Strings are one of the most commonly used data types in Python. A string is used to store text data such as names, messages, addresses, or any sequence of characters. In simple words, anything written inside quotation marks in Python is considered a string.
Strings are widely used in real world applications such as user input, data processing, reporting systems, and web development.
CREATING STRINGS
In Python, strings are created by enclosing text inside single quotes or double quotes.
Examples:
name = “Hira”
city = ‘Karachi’
message = “Welcome to Python”
Both single and double quotes work the same way.
MULTILINE STRINGS
If you want to write text on multiple lines, you can use triple quotes.
Example:
text = “””Python is easy to learn
It is powerful and flexible
It is widely used worldwide”””
ACCESSING CHARACTERS IN A STRING
Each character in a string has a position called an index. Indexing starts from 0.
Example:
word = “Python”
print(word[0])
Output will be P.
STRING CONCATENATION
You can join two or more strings using the plus operator.
Example:
first_name = “Hira”
last_name = “Khan”
full_name = first_name + ” ” + last_name
This combines both strings into one.
STRING METHODS
Python provides many built in functions to work with strings.
upper() converts text to uppercase
lower() converts text to lowercase
strip() removes extra spaces
replace() replaces part of a string
len() counts the number of characters
Example:
text = “python”
print(text.upper())
Output will be PYTHON.
CHECKING STRING TYPE
You can check the type of a string using the type() function.
Example:
name = “Ali”
print(type(name))
This will show that the variable is of type string.
WHY STRINGS ARE IMPORTANT
Strings are essential for handling text based information in programs. They are used in printing messages, taking user input, storing data, and building applications.
Understanding strings and their operations helps you manage text efficiently and build more interactive Python programs.