top of page

Strings. Chapter 4: Mastering Indexing and Slicing in Python Strings

In this chapter, we'll embark on a thrilling journey into the world of characters that make up strings. We'll unlock the power of indexing and slicing, enabling us to access and manipulate individual characters and specific portions of strings. Get ready to wield precise control over your strings and unleash their true potential.


Indexing is like pinpointing a specific character within a string. In Python, strings are zero-indexed, meaning the first character has an index of 0, the second character has an index of 1, and so on. With indexing, we can retrieve individual characters and perform targeted operations.


For example:


word = "Python"
print(word[0])  # Output: 'P'
print(word[2])  # Output: 't'



Slicing takes string manipulation to the next level by allowing us to extract a substring or a portion of a string. It uses a start and end index to define the range of characters to be extracted. The character at the start index is included, while the character at the end index is excluded.


For example:


sentence = "Python is amazing"
print(sentence[0:6])   # Output: 'Python'
print(sentence[7:])	# Output: 'is amazing'


With slicing, we can extract substrings, reverse strings, or even step through a string with a specified interval.


useful methods:

  • len(): Obtain the length of a string by counting the number of characters. This is useful for determining the size of a string or iterating through it using a loop.


    word = "Hello"
   length = len(word)
   print(length)  # Output: 5

  • in: Check if a character or substring exists within a string using the `in` keyword. This allows for quick membership checks without the need for explicit searching.


   sentence = "Python is amazing"
   print("amazing" in sentence)  # Output: True


By mastering indexing and slicing techniques, along with these honorary mentions, you'll gain the ability to navigate, extract, and manipulate characters with precision and finesse.


Exercise:

Formatting Usernames Write a Python program that takes a list of usernames as input. The program should format each username by removing leading and trailing whitespace, converting it to lowercase, and replacing spaces with underscores. The formatted usernames should be stored in a new list and displayed as output.

Example: Input: Enter a list of usernames (separated by commas): John Doe, Jane Smith, Mike123, Emily_21 Output: Formatted usernames: john_doe, jane_smith, mike123, emily_21

Hint: You can use string methods like strip(), lower(), and replace() to perform the required formatting operations on each username. Iterate through the list of usernames using a loop and apply the formatting to each username before appending it to the new list.



Comments


Subscribe to QABites newsletter

Thanks for submitting!

  • Twitter
  • Facebook
  • Linkedin

© 2023 by QaBites. Powered and secured by Wix

bottom of page