- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 −
Example
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)
Output
The string is Hi there how are you The new string is Hiou
Explanation
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.
- Related Articles
- Python Program to Form a New String where the First Character and the Last Character have been Exchanged
- Program to remove duplicate characters from a given string in Python
- C++ program to check if first and the last characters of string are equal
- How to get last 2 characters from string in C# using Regex?
- Python program to extract characters in given range from a string list
- Java program to delete duplicate characters from a given String
- 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 extract the last n characters from a string using Java?
- C++ program to Reorder the Given String to Form a K-Concatenated String
- Java Program to replace only first occurrences of given String with new one
- Check whether second string can be formed from characters of first string in Python
- Extract only characters from given string in Python
- MySQL query to get a substring from a string except the last three characters?
- How to extract the first n characters from a string using Java?

Advertisements