Skip to content

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

  • by

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.


slice(start_pos, stop_pos, step)


  • 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 are None.

Return value

It returns a range of characters(substring).

Create a slice object for slicing

# contains indices (0, 1, 2)
obj1 = slice(3)

# contains indices (1, 3)
obj2 = slice(1, 5, 2)
print(slice(1, 5, 2))


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:

b = "Hello, World!"

Output: Hello

2. Get substring using slice object

stop = 3
str = 'Python'

slice_obj = slice(3)

Output: Pyt

start = 1, stop = 6, step = 2
str = 'Python'

slice_obj = slice(1, 6, 2)

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

str = 'Hi Python !'

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

str.split([separator [, maxsplit]])

Complete example: Splits at comma  ‘,’

str1 = 'Split, Python string'

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

Read more: Python Split() Function and String Example

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

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

Your email address will not be published. Required fields are marked *