Python slice string Function| Get a range of characters (SubString)

You can get a range of characters(substring) by using the slice function. Python slice() function returns a slice object that can use used to slice strings, lists, tuples.

You have to Specify the parameters- start index and the end index, separated by a colon, to return a part of the string.

Syntax

Parameters

  • start (optional) – Integer value to start the slicing of the object. Default is None.
  • stop – Integer value for stop position. The slicing stops at index stop -1 (last element).
  • step (optional) – Integer value to provide determines the increment between each index. Defaults is None.

Return value

It returns a range of characters(substring).

Create a slice object for slicing

Output:

Python slice string Function

Examples of Python slice string

Let’s see multiple example of it:-

1. Shortest Way string slicing

Get the characters from position 0 to 5:

Output: Hello

2. Get substring using slice object

Output: Pyt

Output: yhn

Q: How to get a substring of the given string in Python?

Answer: You can get python substring by using a split() function or Indexing. 

Complete example

Output: H

Read more: Python Substring and Examples

Q: What is Python string split?

Answer: The Python split() function breaks up a string at the specified separator space, and returns a list of Strings

Complete example: Splits at comma  ‘,’

Output : [‘Split’, ‘ Python string’]

Read more: Python Split() Function and String Example

Do comment if you have any doubts and suggestions on this tutorial.

Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.