Introduction
In Python, a string is a sequence of characters enclosed within single quotes, double quotes, or triple quotes.
Strings are used to store text, such as names, addresses, messages, and sentences.
Python supports three ways to create strings:
- Single quotes (
' ') - Double quotes (
" ") - Triple quotes (
''' '''or""" """)
Example
name = 'maha'
name2 = "lakshmi"
print(name)
print(name2)
print(type(name))
print(type(name2))
Output:
maha
lakshmi
<class 'str'>
<class 'str'>
Explanation
-
namestores the stringmahausing single quotes. -
name2stores the stringlakshmiusing double quotes. - The
type()function identifies the datatype of a variable. - Both variables belong to the
strdatatype.
Note: In Python, datatypes are represented by classes. For example, str is the class used for string objects.
2. String Methods
Python provides several built-in string methods to perform operations on strings.
One such method is capitalize().
Example: capitalize()
name = "maha"
print(name.capitalize())
Output:
Maha
Explanation
The capitalize() method converts the first character of a string to uppercase and the remaining characters to lowercase.
Important: Strings are immutable in Python. This means we cannot modify the original string directly. String methods return a new string.
3. Multiline Strings
Sometimes we need to store multiple lines of text in a single variable.
For this purpose, Python supports triple quotes.
Example
address = """7, Vivekanandar Street,
West Tambaram,
Chennai"""
print(address)
Output:
7, Vivekanandar Street,
West Tambaram,
Chennai
Explanation
- Triple quotes allow us to write strings across multiple lines.
- Line breaks are preserved in the string.
- Multiline strings are useful for storing addresses, paragraphs, and long messages.
4. What Is String Indexing?
Indexing is used to access individual characters from a string.
In Python, every character in a string has an index position.
Python supports two types of indexing:
- Positive indexing
- Negative indexing
Positive Indexing
Positive indexing starts from 0, moving from left to right.
Consider the following string:
word = 'python'
Positive index positions
| Character | p | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
Negative Indexing
Negative indexing starts from -1, moving from right to left.
| Character | p | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Index | -6 | -5 | -4 | -3 | -2 | -1 |
Example
word = 'abcdefghijklmnopqrstuvwxyz'
print(word[1])
print(word[5])
print(word[-2])
Output:
b
f
y
Explanation
-
word[1]returns the character at index 1, which isb. -
word[5]returns the character at index 5, which isf. -
word[-2]returns the second character from the end, which isy.
Important: If we try to access an index that does not exist, Python raises an IndexError.
5. What Is String Slicing?
Slicing is used to extract a part of a string.
Syntax
string[start:stop:step]
Here:
-
start: The index where slicing begins. -
stop: The index where slicing ends. The stop position is not included. -
step: The number of positions to move each time.
Example 1: Basic Slicing
word = 'abcdefghijklmnopqrstuvwxyz'
print(word[1:5])
Output:
bcde
Explanation:
- Slicing starts at index 1.
- It stops before index 5.
- Therefore, the characters at indexes 1, 2, 3, and 4 are returned.
Example 2: Slicing with Step
word = 'abcdefghijklmnopqrstuvwxyz'
print(word[2:10:2])
Output:
cegi
Explanation:
- Starting index is 2.
- Ending index is 10 (not included).
- Step value is 2.
- Python selects every second character.
Example 3: Start Value Greater Than Stop Value
word = 'abcdefghijklmnopqrstuvwxyz'
print(word[20:2])
Output:
(empty string)
Explanation:
The default step is positive 1, so Python moves from left to right.
Since the starting index 20 is greater than the stopping index 2, no characters are selected.
Example 4: Slicing with Step 2
word = 'abcdefghijklmnopqrstuvwxyz'
print(word[20::2])
Output:
uwy
Explanation:
Python starts at index 20 and moves forward by 2 positions until the end of the string.
Example 5: Negative Slicing
word = 'abcdefghijklmnopqrstuvwxyz'
print(word[-1:-10:-2])
Output:
zxvtr
Explanation:
- Starting index is -1.
- Stopping index is -10 (not included).
- Step is -2.
- A negative step moves from right to left.
6. Reversing a String Using Slicing
We can reverse a string using slicing with a negative step.
Example
name = 'python'
print(name)
print(name[-1:])
print(name[-1::-1])
print(name[::-1])
print(name[-1::])
Output:
python
n
nohtyp
nohtyp
n
Explanation
1. name
Prints the complete string.
2. name[-1:]
Starts from the last character and takes the remaining characters. Since it is already at the end, only n is returned.
3. name[-1::-1]
Starts from the last character and moves backwards through the string.
4. name[::-1]
Reverses the entire string using a negative step.
5. name[-1::]
Starts from the last character and moves forward. Therefore, it returns only n.
Top comments (0)