Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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 program to read character by character from a file
Next article icon

Python Program To Remove all control characters

Last Updated : 14 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In the telecommunication and computer domain, control characters are non-printable characters which are a part of the character set. These do not represent any written symbol. They are used in signaling to cause certain effects other than adding symbols to text. Removing these control characters is an essential utility. In this article, we will discuss how to remove all those control characters.

Example:

Input : test_str = ‘Geeks\0\r for \n\bge\tee\0ks\f’

Output : Geeks for geeeks

Explanation : \n, \0, \f, \r, \b, \t being control characters are removed from string.

Input : test_str = ‘G\0\r\n\fg’

Output : Gfg

Explanation : \n, \0, \f, \r being control characters are removed from string, giving Gfg as output.

Method 1 : Using translate().

The logic applied here is that each non-control character is at the top 33 ASCII characters, hence translation is used to avoid all others except these via mapping.

Python3




# Python3 code to demonstrate working of
# Remove all control characters
# Using translate()
 
# initializing string
test_str = 'Geeks\0\r for \n\bge\tee\0ks\f'
 
# printing original string
print("The original string is : " + str(test_str))
 
# using translate() and fromkeys()
# to escape all control characters
mapping =  dict.fromkeys(range(32))
res = test_str.translate(mapping)
 
# printing result
print("String after removal of control characters : " + str(res))
 
 

Output:

 for original string is : Geeks ge    eeks String after removal of control characters : Geeks for geeeks

Method 2: Using unicodedata library

In this, using unicodedata.category(), we can check each character starting with “C” is the control character and hence be avoided in the result string.

Python3




# Python3 code to demonstrate working of
# Remove all control characters
# Using unicodedata library
import unicodedata
 
# initializing string
test_str = 'Geeks\0\r for \n\bge\tee\0ks\f'
 
# printing original string
print("The original string is : " + str(test_str))
 
# surpassing all control characters
# checking for starting with C
res = "".join(char for char in test_str if unicodedata.category(char)[0]!="C")
 
# printing result
print("String after removal of control characters : " + str(res))
 
 

Output:

 for original string is : Geeks ge    eeks String after removal of control characters : Geeks for geeeks

Method 3: Using Regular Expression

In this, using re library’s sub() function, we can remove all those control characters which are identified with \x format.

Python3




# Python3 code to demonstrate working of
# Remove all control characters
# Using Regular Expression
import re
  
# initializing string
test_str = 'Geeks\0\r for \n\bge\tee\0ks\f'
  
# printing original string
print("The original string is : " + str(test_str))
  
# surpassing all control characters
# using sub()
res = re.sub(r'[\x00-\x1f]', '', test_str)
  
# printing result
print("String after removal of control characters : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
 
 

Time Complexity: O(N)
Space Complexity: O(N)



Next Article
Python program to read character by character from a file
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python program to remove last N characters from a string
    In this article, we’ll explore different ways to remove the last N characters from a string in Python. This common string manipulation task can be achieved using slicing, loops, or built-in methods for efficient and flexible solutions. Using String SlicingString slicing is one of the simplest and mo
    2 min read
  • Python program for removing i-th character from a string
    In this article, we will explore different methods for removing the i-th character from a string in Python. The simplest method involves using string slicing. Using String SlicingString slicing allows us to create a substring by specifying the start and end index. Here, we use two slices to exclude
    2 min read
  • Python program to read character by character from a file
    Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file character by character. In this article, we will cover a few examples of it. Example Input: GeeksOutput: G e e k sExplanation: Iterated through character by charact
    2 min read
  • Remove words containing list characters - Python
    In this article, we will explore various methods to remove words containing list characters in Python. The simplest way to do is by using a loop. Using a LoopIterate over each word in the list and check if it contains any of the characters from remove_chars. If a word contains any of those character
    2 min read
  • Python Program to Find ASCII Value of a Character
    Given a character, we need to find the ASCII value of that character using Python. ASCII (American Standard Code for Information Interchange) is a character encoding standard that employs numeric codes to denote text characters. Every character has its own ASCII value assigned from 0-127. Examples:
    2 min read
  • Python - Remove N characters after K
    Given a String, remove N characters after K character. Input : test_str = 'ge@987eksfor@123geeks is best@212 for cs', N = 3, K = '@' Output : 'geeksforgeeks is best for cs' Explanation : All 3 required occurrences removed. Input : test_str = 'geeksfor@123geeks is best for cs', N = 3, K = '@' Output
    2 min read
  • Python Program for Convert characters of a string to opposite case
    Given a string, convert the characters of the string into the opposite case,i.e. if a character is the lower case then convert it into upper case and vice-versa. Examples: Input : geeksForgEeksOutput : GEEKSfORGeEKSInput: hello every oneOutput: HELLO EVERY ONEExample 1: Python Program for Convert ch
    7 min read
  • Remove Multiple Characters from a String in Python
    Removing multiple characters from a string in Python can be achieved using various methods, such as str.replace(), regular expressions, or list comprehensions. Each method serves a specific use case, and the choice depends on your requirements. Let’s explore the different ways to achieve this in det
    3 min read
  • Python Program to find if a character is vowel or Consonant
    Given a character, check if it is vowel or consonant. Vowels are 'a', 'e', 'i', 'o' and 'u'. All other characters ('b', 'c', 'd', 'f' ....) are consonants. Examples: Input : x = 'c'Output : ConsonantInput : x = 'u'Output : VowelRecommended: Please try your approach on {IDE} first, before moving on t
    5 min read
  • Remove All Characters Except Letters and Numbers - Python
    In this article, we’ll learn how to clean a string by removing everything except letters (A–Z, a–z) and numbers (0–9). This means getting rid of: Special characters (@, #, !, etc.)Punctuation marksWhitespaceFor example, consider a string s = "[email protected]", after removing everything except the numbers
    2 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