Home / Programs / Write a Python program which gets from the keyboard which is made the first 2 and the last 2 characters. If the length of the string is less than 2, then the program should return a value. Otherwise, it should return an empty string.
🚀 Programming Example

Write a Python program which gets from the keyboard which is made the first 2 and the last 2 characters. If the length of the string is less than 2, then the program should return a value. Otherwise, it should return an empty string.

👁 380 Views
💻 Practical Program
📘 Step Learning
For instance, if you type “A1resource”, the program should display “A1ce” and if you type A1, the program should display “A1”

💻 Program Code

main.phy
----------

import sys
def main ():
main ()

TypeCast.py
-------------
def strings_onboth_ends(str):
    if len(str) < 2:
     return ""
    return str[0:2] + str[-2:]

print(strings_onboth_ends ("w3resource"))
print(strings_onboth_ends ("w3"))
print(strings_onboth_ends ("w"))



                        

🖥 Program Output

w3ce
w3w3
                            

📘 Explanation

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.