w3resource

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


Get first 3 chars of a string.

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

For more Practice: Solve these Related Problems:

  • Write a Python function to return the first three characters of a string using slicing, or the entire string if its length is less than 3.
  • Write a Python program to extract the first three characters conditionally using a ternary operator.
  • Write a Python program to implement the function recursively that returns the first three characters if available.
  • Write a Python program to use an if-else statement to check string length and output either the first three characters or the original string.

Go to:


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.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.