This is a Python Program to form a new string made of the first 2 characters and last 2 characters from a given string.
The program takes a string and forms a new string made of the first 2 characters and last 2 characters from a given string.
1. Take a string from the user and store it in a variable.
2. Initialize a count variable to 0.
3. Use a for loop to traverse through the characters in the string and increment the count variable each time.
4. Form the new string using string slicing.
5. Print the newly formed string.
6. Exit.
Here is source code of the Python Program to form a new string made of the first 2 characters and last 2 characters from a given string. The program output is also shown below.
string=raw_input("Enter string:") count=0 for i in string: count=count+1 new=string[0:2]+string[count-2:count] print("Newly formed string is:") print(new)
1. User must enter a string and store it in a variable.
2. The count variable is initialized to zero.
3. The for loop is used to traverse through the characters in the string.
4. The count is incremented each time a character is encountered.
5. The new string is formed by using string slicing and the first two letters and the last two letters of the string are concatenated using the ‘+’ operator.
6. The newly formed string is printed.
Case 1: Enter string:Hello world Newly formed string is: Held Case 2: Enter string:Checking Newly formed string is: Chng
No comments:
Post a Comment