Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Expand Character Frequency String
Next article icon

Python - Expand Character Frequency String

Last Updated : 24 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string, which characters followed by its frequency, create the appropriate string.

Examples:

Input : test_str = 'g7f2g3i2s2b3e4' 
Output : gggggggffgggiissbbbeeee 
Explanation : g is succeeded by 7 and repeated 7 times.

Input : test_str = 'g1f1g1' 
Output : gfg 
Explanation : f is succeeded by 1 and repeated 1 time. 

Method #1: Using zip() + join()

This is one of the ways in which this task can be performed. In this, the task of joining appropriate characters is done using join() and zip() is used to convert different frequency and character strings. The drawback is that frequency of character is restricted to a 1-digit number in this.

Python3
# Python3 code to demonstrate working of  # Expand Character Frequency String  # Using join() + zip() import re  # initializing string test_str = 'g7f2g3i2s2b3e4s5t6'  # printing original string print("The original string is : " + str(test_str))  # using zip() to pair up numbers and characters  # separately res = "".join(a *int(b) for a, b in zip(test_str[0::2], test_str[1::2]))  # printing result  print("The expanded string : " + str(res))  

Output
The original string is : g7f2g3i2s2b3e4s5t6 The expanded string : gggggggffgggiissbbbeeeessssstttttt

Time Complexity: O(n)

Auxiliary Space: O(n)

Method #2: Using regex() + join()

This is yet another way in which this task can be performed. In this task of pairing numbers and characters to different strings is performed using regex() and the advantage is that it can take numbers with digits more than 2.

Python3
# Python3 code to demonstrate working of  # Expand Character Frequency String  # Using regex() + join() import re  # initializing string test_str = 'g7f2g3i2s2b3e4s5t10'  # printing original string print("The original string is : " + str(test_str))  # using findall to pair up numbers and characters  # separately, can include longer digit strings res = ''.join(chr * int(num or 1)                for chr, num in re.findall(r'(\w)(\d+)?', test_str))  # printing result  print("The expanded string : " + str(res))  

Output
The original string is : g7f2g3i2s2b3e4s5t10 The expanded string : gggggggffgggiissbbbeeeessssstttttttttt

Time Complexity: O(n)

Auxiliary Space: O(n)

Method #3: Without using any built-in methods

Python3
# Python3 code to demonstrate working of # Expand Character Frequency String  # initializing string test_str = 'g7f2g3i2s2b3e4s5t6'  # printing original string print("The original string is : " + str(test_str)) character=[] frequency=[] for i in range(0,len(test_str)):     if(i%2==0):         character.append(test_str[i])     else:         frequency.append(int(test_str[i])) res="" for i in range(0,len(character)):     res+=character[i]*frequency[i] # printing result print("The expanded string : " + str(res)) 

Output
The original string is : g7f2g3i2s2b3e4s5t6 The expanded string : gggggggffgggiissbbbeeeessssstttttt

Time Complexity: O(n)

Auxiliary Space: O(n)

Method #4: Using itertools.repeat()

In this method, we use the itertools.repeat() method to repeat the characters according to their frequency. The itertools.repeat() method takes two arguments, the first argument is the element to repeat and the second argument is the number of times to repeat the element.

Python3
#Python3 code to demonstrate working of #Expand Character Frequency String #Using itertools.repeat() import re import itertools  #initializing string test_str = 'g7f2g3i2s2b3e4s5t6' # #printing original string print("The original string is : " + str(test_str))  #using itertools.repeat to repeat characters #according to their frequency res = ''.join("".join(itertools.repeat(c, int(num))) for c, num in zip(test_str[::2], test_str[1::2]))    #printing result print("The expanded string : " + str(res)) 

Output
The original string is : g7f2g3i2s2b3e4s5t6 The expanded string : gggggggffgggiissbbbeeeessssstttttt

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 5 :  without using itertools.repeat() 

Create an empty string to store the expanded string.
Loop through the string test_str with a step of 2 to iterate over the characters.
For each character, get the corresponding frequency from the next character in the string (test_str[i+1]).
Loop i times and append the character to the expanded string.
Return the expanded string.

Python3
#Python3 code to demonstrate working of #Expand Character Frequency String #Without using itertools.repeat()  #initializing string test_str = 'g7f2g3i2s2b3e4s5t6'  #printing original string print("The original string is : " + str(test_str))  #expanding the string expanded_str = "" for i in range(0, len(test_str), 2):     char = test_str[i]     freq = int(test_str[i+1])     for j in range(freq):         expanded_str += char  #printing result print("The expanded string : " + str(expanded_str)) 

Output
The original string is : g7f2g3i2s2b3e4s5t6 The expanded string : gggggggffgggiissbbbeeeessssstttttt 

The time complexity of this approach is O(n^2), where n is the length of the input string. 

The auxiliary space complexity is O(n), where n is the length of the input string.


Next Article
Python - Expand Character Frequency String

M

manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

    Maximum Frequency Character in String - Python
    The task of finding the maximum frequency character in a string involves identifying the character that appears the most number of times. For example, in the string "hello world", the character 'l' appears the most frequently (3 times).Using collection.CounterCounter class from the collections modul
    3 min read
    Python - Least Frequent Character in String
    The task is to find the least frequent character in a string, we count how many times each character appears and pick the one with the lowest count.Using collections.CounterThe most efficient way to do this is by using collections.Counter which counts character frequencies in one go and makes it eas
    3 min read
    Python - Successive Characters Frequency
    Sometimes, while working with Python strings, we can have a problem in which we need to find the frequency of next character of a particular word in string. This is quite unique problem and has the potential for application in day-day programming and web development. Let's discuss certain ways in wh
    6 min read
    Python | Construct string from character frequency tuple
    Sometimes, while working with data, we can have a problem in which we need to perform construction of string in a way that we have a list of tuple having character and it's corresponding frequency and we require to construct a new string from that. Let's discuss certain ways in which this task can b
    5 min read
    Python - Characters Index occurrences in String
    Sometimes, while working with Python Strings, we can have a problem in which we need to check for all the characters indices. The position where they occur. This kind of application can come in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using set() + reg
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences