- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to Form a New String Made of the First 2 and Last 2 characters From a Given String
When it is required to form a new string that is made from the first two and last two characters of a given string, a counter can be defined, and indexing can be used to access specific range of elements.
Below is the demonstration of the same −
my_string = "Hi there how are you" my_counter = 0 for i in my_string: my_counter = my_counter + 1 new_string = my_string[0:2] + my_string [my_counter - 2: my_counter ] print("The string is ") print(my_string) print("The new string is ") print(new_string)
The string is Hi there how are you The new string is Hiou
A string is defined and is displayed on the console.
A counter is initiated to 0.
The string is iterated over, and the first 2 and last two elements are accessed using indexing.
This is assigned to a variable.
It is the output that is displayed on the console.
- Python Program to Form a New String where the First Character and the Last Character have been Exchanged
- How to get last 2 characters from string in C# using Regex?
- C++ program to check if first and the last characters of string are equal
- Program to remove duplicate characters from a given string in Python
- Python program to extract characters in given range from a string list
- Java program to delete duplicate characters from a given String
- Find all palindromic sub-strings of a given string - Set 2 in Python
- 2’s compliment for a given string using XOR ?
- Program to find a good string from a given string in Python
- Check if characters of a given string can be rearranged to form a palindrome in Python
- How to ORDER BY last 2 character string in MySQL?
- How to extract the last n characters from a string using Java?
- Python Program to Find the first Common Element between the 2 given Linked Lists
- Python program to count upper and lower case characters in a given string.
- Check if a given string is made up of two alternating characters in C++