w3resource

Python: Get a string made of its first three characters of a specified string

Python String: Exercise-18 with Solution

Write a Python function to get a string made of the first three characters of a specified string. If the length of the string is less than 3, return the original string.

Python String Exercises: Get a string made of its first three characters of a specified string

Sample Solution:

Python Code:

# Define a function named first_three that takes one argument, 'str'.
def first_three(str):
    # Check if the length of the input string 'str' is greater than 3.
    if len(str) > 3:
        # If the string is longer than 3 characters, return the first three characters using slicing.
        return str[:3]
    else:
        # If the string is 3 characters or shorter, return the entire string.
        return str

# Call the first_three function with different input strings and print the results.
print(first_three('ipy'))      # Output: 'ipy'
print(first_three('python'))   # Output: 'pyt'
print(first_three('py'))       # Output: 'py'

Sample Output:

ipy                                                                                                           
pyt                                                                                                           
py 

Flowchart:

Flowchart: Function to get a string made of its first three characters of a specified string

Python Code Editor:

Previous: Write a Python function to get a string made of 4 copies of the last two characters of a specified string (length must be at least 2).
Next: Write a Python program to get the last part of a string before a specified character.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/string/python-data-type-string-exercise-18.php