Thursday, 9 January 2025

Day 81: Python Program to Create a New String Made up of First and Last 2 Characters

 

def create_new_string(input_string):

    if len(input_string) < 2:

        return ""

    return input_string[:2] + input_string[-2:]

user_input = input("Enter a string: ")

result = create_new_string(user_input)

print("New string:", result)

#source code --> clcoding.com 


Code Explanation:

1. Defining the Function
The function create_new_string does the main task of creating the new string.

def create_new_string(input_string):
    if len(input_string) < 2:
        return ""
    return input_string[:2] + input_string[-2:]

Step 1: Check the Length of the String
if len(input_string) < 2:
    return ""
len(input_string) calculates the number of characters in the input string.
If the length is less than 2, the function immediately returns an empty string ("") because there aren’t enough characters to extract the required parts.

Step 2: Extract the First and Last Two Characters
return input_string[:2] + input_string[-2:]
input_string[:2]: Extracts the first two characters of the string.
input_string[-2:]: Extracts the last two characters of the string.
Combine the Parts: The + operator joins the first two and last two characters into a single string.

2. Taking User Input
The program prompts the user to enter a string:
user_input = input("Enter a string: ")
The user’s input is stored in the variable user_input.

3. Generating the New String
The function create_new_string is called with user_input as its argument:
result = create_new_string(user_input)
The resulting new string (or an empty string if the input is too short) is stored in the variable result.

4. Displaying the Output
Finally, the program prints the result:
print("New string:", result)

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (80) AI (35) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (179) C (77) C# (12) C++ (82) Course (67) Coursera (231) Cybersecurity (24) data management (11) Data Science (129) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML Quiz (1) HTML&CSS (47) IBM (30) IoT (1) IS (25) Java (93) Java quiz (1) Leet Code (4) Machine Learning (61) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) pyth (1) Python (953) Python Coding Challenge (398) Python Quiz (53) Python Tips (3) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses