Python | Get the substring from given string using list slicing

Python | Get the substring from given string using list slicing

To extract a substring from a given string using list slicing in Python, you can treat the string just like a list. Strings are essentially sequences of characters, and you can use indexing and slicing on them just as you would with lists.

Here's a basic example:

s = "Hello, World!" # Extract the substring "Hello" substring = s[0:5] print(substring) # Outputs: Hello # Extract the substring "World" substring = s[7:12] print(substring) # Outputs: World 

In this example:

  • s[0:5] extracts characters from index 0 (inclusive) to index 5 (exclusive).
  • s[7:12] extracts characters from index 7 (inclusive) to index 12 (exclusive).

Note: Remember that string indices in Python are 0-based. The first character has index 0, the second has index 1, and so on.


More Tags

web-manifest sql-function webdriver geodjango glassfish android-architecture-navigation qgis language-agnostic ruby-on-rails-6 spring-cloud

More Programming Guides

Other Guides

More Programming Examples