Home » Python » Python programs

Python program for slicing a string

Here, we are going to learn how to slice a string till given number of characters from the front using python program?
Submitted by Suryaveer Singh, on June 08, 2019

Given a string and number of characters (N), we have to slice and print the starting N characters from the given string using python program.

SLICING:

Slicing can be defined as selecting specific characters of a string. This can be performed easily by knowing the length of a string also if the length is not specified initially we can do it by selecting the number of characters that we require.

Now let's understand slicing with a simple example,

Question:

We are provided with a string such that the first N characters are the front characters of the string. If the provided string length is less than N, the front is whatever we have got. Now your task is to create a new string such that it contains only the N characters from the front.

Example:

    slice('Javan', 3) = 'Jav'
    slice('Chocolava', 5) = 'Choco'
    slice('jio', 6) = 'jio'

Solution:

Here we have considered N as a number of the front end. Here as the length of the string is not mentioned initially so here we have done slicing by considering a specific number of characters.

Code:

def slice(str, n):
    if len(str) < n:
        n = len(str)
    front = str[:n]
    return front


print (slice('Chocolate', 5))
print (slice('IncludeHelp', 7))
print (slice('Hello', 10)) #will print all characters

Output

Choco
Include
Hello





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.