❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Indexing and slicing

27 July 2024 at 02:48

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:

word = K A V I N
       ^ ^ ^ ^ ^
index= 1 2 3 4 5 

Basic Indexing
eg:

name="kavin"
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:

name="kavin"
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:

word='Indexing'
print(word[0]) 
print(word[-1])  
print(word[2])
print(word[-3]) 

 'I'
 'g'
 'd'
 'i'

Real-World Examples

** Initials of a Name**
eg:

full_name = "Parotta Salna"
initials = full_name[0] + full_name[8]
print(initials) 

PS

Accessing File Extensions
eg:

filename = "document.pdf"
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:

string[start:stop]

Where:

start is the index where the slice begins (inclusive).
stop is the index where the slice ends (exclusive).

Simple Slicing
eg:

text = "Hello, World!"
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:

text = "Python Programming"
print(text[:6])  

'Python'

Slicing with Step

You can include a step to specify the interval between characters in the slice. The syntax is:

string[start:stop:step]

eg:

text = "abcdefghij"
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:

text = "Python"
print(text[-3:])  

'hon'

eg with reversing a string :

text = "Reverse"
print(text[::-1]) 

'esreveR'

Real-World Examples

1.Extracting File Extensions

filename = "report.pdf"
extension = filename[-3:]
print(extension)  

'pdf'

2.Getting a Substring

quote = "To be or not to be, that is the question."
substring = quote[9:17]
print(substring)  

'not to be'

3.Parsing Dates

date = "20230722"
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

text = "abcdef"
print(text[::2]) 

'ace'

2.Slicing with Negative Step

text = "abcdefghij"
print(text[::-2])  

'jhfdb'

This the things which I learnt I my class.
Thank you

Tasks – Indexing & Slicing

22 July 2024 at 10:37
  1. Write a function that takes a string and returns a new string consisting of its first and last character.
  2. Write a function that reverses a given string.
  3. Given a string, extract and return a substring from the 3rd to the 8th character (inclusive).
  4. Write a function that returns every second character from a given string.
  5. Write a function that replaces the middle third of a string with asterisks. If the length of the string is not divisible by 3, adjust the middle third accordingly.
  6. Write a function that checks if a given string is a palindrome (reads the same backward as forward).
  7. Given an email address, extract and return the domain.
  8. Write a function that returns every third character from a given string.
  9. Write a function that extracts and returns characters at even indices from a given string.
  10. Write a function that skips every second character and then reverses the resulting string.

Python – Indexing & Slicing

22 July 2024 at 10:32

Indexing & Slicing in general is a foundational concept which roots to the usage of all data structures or containers.

Indexing & Slicing is a fundamental concept in Python, especially when working with strings.

If you’re just getting started with Python, understanding how to access individual characters in a string using indexing is important.

What is 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. Python uses zero-based indexing, which means the first character of a string has an index of 0, the second character has an index of 1, and so on.

For Eg, Check the below β€œHELLOWORLD” and its index,

Basic Indexing

Let’s start with a simple example:


# Example String
word = "Python"

# Accessing individual characters
print(word[0])  # Output: 'P'
print(word[1])  # Output: 'y'
print(word[2])  # Output: 't'
print(word[3])  # Output: 'h'
print(word[4])  # Output: 'o'
print(word[5])  # Output: 'n'

In this example, we accessed each character of the string β€œPython” using its index.

Negative Indexing

Python also supports negative indexing, which allows you to access characters from the end of the string. The last character has an index of -1, the second last character has an index of -2, and so on.


# Example String
word = "Python"

# Accessing characters from the end
print(word[-1])  # Output: 'n'
print(word[-2])  # Output: 'o'
print(word[-3])  # Output: 'h'
print(word[-4])  # Output: 't'
print(word[-5])  # Output: 'y'
print(word[-6])  # Output: 'P'

Combining Positive and Negative Indexing

You can mix positive and negative indexing to access different parts of a string. Here are some examples:


# Example String
word = "Indexing"

# Accessing characters using positive and negative indices
print(word[0])  # Output: 'I'
print(word[-1])  # Output: 'g'
print(word[2])  # Output: 'd'
print(word[-3])  # Output: 'i'

Real-World Examples

Let’s look at some practical examples where indexing might be useful.

Example 1: Initials of a Name

Suppose you have a person’s full name, and you want to extract the initials.


full_name = "Parotta Salna"
initials = full_name[0] + full_name[8]
print(initials)  # Output: 'PS'

In this example, we used indexing to access the first letter of the first name and the first letter of the last name.

Example 2: Accessing File Extensions

Consider a filename with an extension, and you want to extract the extension.


filename = "document.pdf"
extension = filename[-3:]
print(extension)  # Output: 'pdf'

Here, we used negative indexing to get the last three characters of the string, which represent the file extension.

What is Slicing ?

Slicing enables you to create a new string by extracting a subset of characters from an existing string.

You specify a range of indices and, optionally, a step to determine how slicing should proceed.

For eg,

Below is the β€œHELLOWORLD” String referenced by variable message, and β€œLOWO” is a subset which can be represented as message[3:7]

Basic Slicing

The basic syntax for slicing is:


string[start:stop]

Where:

  • start is the index where the slice begins (inclusive).
  • stop is the index where the slice ends (exclusive).

Example 1: Simple Slicing


# Example String
text = "Hello, World!"

# Slicing the first 5 characters
print(text[0:5])  # Output: 'Hello'

# Slicing characters from index 7 to 11
print(text[7:12])  # Output: 'World'

Omitting Indices

You can omit the start or stop index to slice from the beginning or to the end of the string.

Example 2: Omitting Start or Stop


# Example String
text = "Python Programming"

# Slicing from the beginning to index 6
print(text[:6])  # Output: 'Python'

# Slicing from index 7 to the end
print(text[7:])  # Output: 'Programming'

Slicing with Step

You can include a step to specify the interval between characters in the slice. The syntax is:


string[start:stop:step]

Example 3: Using Step


# Example String
text = "abcdefghij"

# Slicing every second character
print(text[0:10:2])  # Output: 'acegi'

# Slicing every third character
print(text[0:10:3])  # Output: 'adgj'

Negative Indices and Step

Negative indices count from the end of the string, and a negative step allows you to slice in reverse order.

Example 4: Negative Indices


# Example String
text = "Python"

# Slicing the last 3 characters
print(text[-3:])  # Output: 'hon'

# Slicing from the beginning to the second last character
print(text[:-1])  # Output: 'Pytho'

Example 5: Reversing a String


# Example String
text = "Reverse"

# Reversing the string
print(text[::-1])  # Output: 'esreveR'

Real-World Examples

Let’s explore some practical uses of string slicing.

Example 6: Extracting File Extensions


filename = "report.pdf"
extension = filename[-3:]
print(extension)  # Output: 'pdf'

Example 7: Getting a Substring

Suppose you have a long string and want to extract a specific part of it.


quote = "To be or not to be, that is the question."
# Extracting 'not to be'
substring = quote[9:17]
print(substring)  # Output: 'not to be'

Example 8: Parsing Dates

Consider a date string in the format β€œYYYYMMDD” and you want to extract the year, month, and day separately.


date = "20230722"
year = date[:4]
month = date[4:6]
day = date[6:]
print(f"Year: {year}, Month: {month}, Day: {day}")
# Output: Year: 2023, Month: 07, Day: 22

Advanced Slicing Techniques

Example 9: Skipping Characters


# Example String
text = "abcdef"

# Skipping every other character
print(text[::2])  # Output: 'ace'

Example 10: Slicing with Negative Step


# Example String
text = "abcdefghij"

# Reversing every second character
print(text[::-2])  # Output: 'jhfdb'

❌
❌