Here, we will figure out how to cut a string till a given number of characters from the front utilizing python program?
Given a string and number of characters (N), we need to cut and print the beginning N characters from the given string utilizing python program.
SLICING:
Slicing can be characterized as choosing explicit characters of a string. This can be performed effectively by knowing the length of a string additionally
if the length isn’t determined at first we can do it by choosing the number of characters that we require.
Presently how about we comprehend slicing with a straightforward example,
Question:
We are given a string with the end goal that the principal N characters are the front characters of the string. In the event that the gave string, the length is not as much as N, the front is whatever we have. Presently your assignment is to make another string with the end goal that it contains just the N characters from the front.
Example:
slice('Just', 3) = 'Jus'
slice('Tech', 2) = 'Te'
slice('Review', 6) = 'Review'
Arrangement:
Here we have thought about N as some of the front end. Here is the length of the string isn’t referenced at first so here we have done slicing by thinking about a particular number of characters.
Code:
def slice(str, n):
if len(str) < n:
n = len(str)
front = str[:n]
return front
print (slice('Kishan', 5))
print (slice('JustTechReview', 7))
print (slice('Hello', 10)) #will print all characters
Output:
Kisha
JustTec
Hello