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

slice(start_pos, stop_pos, step)

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 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)
print(obj1)

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

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:

b = "Hello, World!"
print(b[0:5])

Output: Hello

2. Get substring using slice object

stop = 3
str = 'Python'

slice_obj = slice(3)
print(str[slice_obj]) 

Output: Pyt

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

slice_obj = slice(1, 6, 2)
print(str[slice_obj])

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. 

string[start:end]
string[:end]

Complete example

str = 'Hi Python !'
 
print(str[0])

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'
print(str1.split(','))

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.