Strings in Python
A string is a sequence of characters enclosed in single quotes (' ')
or double quotes (" "). Strings are used to store text data in Python.
Important Points:
- Strings are immutable (cannot be changed after creation).
- You can use both
'single'or"double"quotes to define strings. - Python also supports
'''triple quotes'''for multi-line strings.
Example of Creating Strings
# Creating different types of strings
platform = "Shiksha"
name = 'Sanchar'
multiline = '''ShikshaSanchar is a learning platform.
This is an example of a multi-line string.'''
print(name)
print(platform)
print(multiline)
Output:
Sanchar
Shiksha
ShikshaSanchar is a learning platform.
This is an example of a multi-line string.
Explanation:
- Strings like
"Shiksha"and'Sanchar'are single-line strings. '''...'''is used to create multi-line strings that span more than one line.
Advantages of Strings in Python
Strings are one of the most commonly used data types in Python. They offer many advantages, such as:
- Easy to create and use: Strings can be created just by enclosing text in quotes.
- Immutability: Strings are immutable, meaning their value cannot be changed — this improves safety and reduces bugs.
- Built-in functions: Python provides many useful built-in functions for
manipulating strings easily (e.g.,
len(),lower(),replace()). - Indexing & Slicing: Easy access to specific characters or substrings using indexing and slicing.
- Flexible formatting: You can format and customize strings using f-strings
or
format()method. - Wide usage: Strings are used in file handling, user inputs, messages, and almost every Python program.