Hi everybody
I am Kavin
I going to write a blog which I learnt in my python class.
Indexing
Indexing is nothing but a position. Indexing refers to accessing individual elements of a sequence, such as a string.
In Python, strings are sequences of characters, and each character in a string has a position, known as an index.
eg:
^ ^ ^ ^ ^
index= 1 2 3 4 5
Basic Indexing
eg:
print(name[0])
print(name[1])
print(name[2])
print(name[3])
print(name[4])
‘k‘
‘a‘
‘v‘
‘i‘
‘n‘
Negative Indexing
Python also supports negative indexing, which allows you to access characters from the end of the string.
eg:
print(name[–1])
print(name[–2])
print(name[–3])
print(name[–4])
print(name[–5])
‘n‘
‘i‘
‘v‘
‘a‘
‘k‘
Combining Positive and Negative Indexing
You can mix positive and negative indexing to access different parts of a string.
eg:
print(word[0])
print(word[–1])
print(word[2])
print(word[–3])
‘I‘
‘g‘
‘d‘
‘i‘
Real-World Examples
** Initials of a Name**
eg:
initials = full_name[0] + full_name[8]
print(initials)
PS
Accessing File Extensions
eg:
extension = filename[–3:]
print(extension)
‘pdf‘
Slicing
Slicing enables you to create a new string by extracting a subset of characters from an existing string.
Basic Slicing
The basic syntax for slicing is:
Where:
start is the index where the slice begins (inclusive).
stop is the index where the slice ends (exclusive).
Simple Slicing
eg:
print(text[0:5])
‘Hello‘
Omitting Indices
You can omit the start or stop index to slice from the beginning or to the end of the string.
eg:
print(text[:6])
‘Python‘
Slicing with Step
You can include a step to specify the interval between characters in the slice. The syntax is:
eg:
print(text[0:10:2])
‘acegi‘
Negative Indices and Step
Negative indices count from the end of the string, and a negative step allows you to slice in reverse order.
eg with Negative Indices:
print(text[–3:])
‘hon‘
eg with reversing a string :
print(text[::–1])
‘esreveR‘
Real-World Examples
1.Extracting File Extensions
extension = filename[–3:]
print(extension)
‘pdf‘
2.Getting a Substring
substring = quote[9:17]
print(substring)
‘not to be‘
3.Parsing Dates
year = date[:4]
month = date[4:6]
day = date[6:]
print(f“Year: {year}, Month: {month}, Day: {day}“)
Year: 2023, Month: 07, Day: 22
Advanced Slicing Techniques
1.Skipping Characters
print(text[::2])
‘ace‘
2.Slicing with Negative Step
print(text[::–2])
‘jhfdb‘
This the things which I learnt I my class.
Thank you