Search code snippets, questions, articles...

Get first N characters from a string in Python

In Python, there are a number of ways to get the first N characters from a string. The most common way is to use the slice operator ([:N]). This operator returns a new string that is a copy of the original string with the first N characters removed.
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

Solution 1: Using slice operator [:N]

If you want to get the first N characters from a string in Python, you can use the slice operator [:N]. This operator returns a new string that is a part of the original string. The new string starts at the beginning of the original string and goes up to, but does not include, the character at index N.

Syntax

input_str[:N]

Code example

my_str = "Welcome user"

# get first 5 characters
result = my_str[:5]

print(result)

Output

Welco

You can also write the above code example as below:

my_str = "Welcome user"

# get first 5 characters
result = my_str[0:5]

print(result)

# Output
# Welco

Solution 2: Get first N characters from a string using For Loop

Here, we will learn how to get the first N characters from a string using a for loop in Python. We will take an input string from the user and then print the first N characters from that string using a Python For loop.

Code example

my_str = "Welcome user"

N = 4
result = ""

counter = 0
for item in my_str:
    if counter < N:
        result += item
    else:
        break

    counter = counter + 1

print(result)

Output

Welc

This code example takes a string, my_str, and prints out the first four characters of the string. The code does this by looping through each character in the string and adding it to the result string. If the counter variable is greater than or equal to four, the code breaks out of the loop and prints the result string.

Solution 3: Get the first N characters using slice() function

The slice() function is used to get the first N characters from a string. This is useful when you want to extract a certain amount of characters from a string.

Code example

my_str = "Welcome user"

slc = slice(4)

# get first 4 characters
result = my_str[slc]

print(result)

# Output
# Welc

Output

Welc

This code example is using the slice function to get the first 4 characters of the string "Welcome user". The result is then printed to the console.

# create a string
my_str = "devsheet"

# get first 4 characters
result = my_str[0:4]

print(result)

# Output
# devs
Was this helpful?
0 Comments