
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to merge strings alternately using Python
Suppose we have two strings s and t. We have to merge them by adding letters in alternating fashion, starting from s. If s and t are not of same length, add the extra letters onto the end of the merged string.
So, if the input is like s = "major" t = "general", then the output will be "mgaejnoerral", as t is larger than s, so we have added extra part "ral" at the end.
To solve this, we will follow these steps −
i := j := 0
result := blank string
while i < size of s and j < size of t, do
result := result concatenate s[i] concatenate t[j]
i := i + 1
j := j + 1
while i < size of s, do
result := result concatenate s[i]
i := i + 1
while j < size of t , do
result := result concatenate t[j]
j := j + 1
return result
Let us see the following implementation to get better understanding −
Example
def solve(s, t): i = j = 0 result = "" while i < len(s) and j < len(t): result += s[i] + t[j] i+=1 j+=1 while i < len(s): result += s[i] i += 1 while j < len(t): result += t[j] j += 1 return result s = "major" t = "general" print(solve(s, t))
Input
"major", "general"
Output
mgaejnoerral
- Related Questions & Answers
- Program to find largest merge of two strings in Python
- Program to merge two strings in alternating fashion in Python
- Python - Ways to merge strings into list
- Program to get maximum length merge of two given strings in Python
- Largest Merge of Two Strings in Python
- Python program to merge to dictionaries.
- Python program to merge two Dictionaries
- Python Program for Merge Sort
- Program to split two strings to make palindrome using Python
- How to merge two strings alternatively in JavaScript
- Python Program to Group Strings by K length Using Suffix
- Python Program for Iterative Merge Sort
- Program to merge K-sorted lists in Python
- How to merge two JSON strings in an order using JsonParserSequence in Java?
- Largest Merge of Two Strings in C++