Skip to content

Python cut the string to length | Example code

  • by

Use syntax string[x:y] to slice a string starting from index x up to but not including the character at index y. If you want only to cut the string to length in python use only string[: length].

string[x:y]

Python cut the string to length Example

Simple example code. Cut the string by 5 lengths. If index x is not specified it defaults to zero.

text = "Hello Python developer"

cut_str = text[:5]

print(cut_str)

Output:

Python cut the string to length

Cut a string starting from index 5 to 10

text = "Hello Python developer"

cut_str = text[5:10]

print(cut_str)

Output: Pyth

Do comment if you have any doubts and suggestions on this Python string topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading