Hi, in this article we will learn Python Program to Get a String Made of The First 2 And The Last 2 Chars From a Given a String.
If The String Length is Less Than 2, Return Instead of The Empty String
The problem statement is given a string you have to gt first two characters and last two characters of that string and return it. If the length of the string is less than 2 then return the null string ""
To get the first two and last two characters of a string we can use string slicing method [:2] and [-2:] will get the first two and last two characters of string respectively.
Phase 1 : Define the function to take input argument as string and return the string. If string length is less than 2 return empty string. else return the first two and last two characters.
def get_string(text):
if len(text) < 2:
return ""
return text[:2] + text[-2:]
Phase 2 : In this section of implementation ask user to enter a string and accept it. Then call the function get_string() by providing the string input to the function.
my_string = input("Enter a string :")
print("New modified string is : ", get_string(my_string))
Final program :
OUTPUT : Run 1
Enter a string :hello
New modified string is : helo
OUTPUT : Run 2
Enter a string :funny
New modified string is : funy
Conclusion : Hope you understood the program completely. If you got any queries comment down below.
0 Comments