Showing posts with label non-printable. Show all posts
Showing posts with label non-printable. Show all posts

Tuesday, March 12, 2013

Python: Remove Non-printable characters from string

Current post is on how to remove non-printable characters from string.


Need a function to remove non-printable characters in python.


Remove Non-printable function for ASCII String:


def    remove_ascii_non_printable(str)
      """Removes Non-printable chars from ASCII String"""
      return ''.join([ch for ch in str if ord(ch) > 31 and ord(ch) < 126 or ord(c) = = 9])

Remove Non-printable function for Unicode String:



def    remove_unicode_non_printable(str)
      """Removes Non-printable chars from ASCII String"""
      return ''.join([ch for ch in str if ord(ch) > 31 or ord(c) = = 9])



Appreciate your feedback via comments.

Thanks.

Thursday, February 25, 2010

Non-Printable Char to int Conversion Issue in C

Current post is on non-printable character conversion to int issue in C language.


By the topic you will assume, what is this? Even a C student who has just started will know that, there is no harm, as we are upgrading the type from character (char) to integer (int).

However, many people including the advanced programmer do not know is that: “conversion of character having non-printable value to int is machine dependent”.

It means that if you take a variable:

char mynonprintablechar = 129;

And then you try to upgrade to int implicitly, the results which you get, will make you scratch your hair.

Example 1: If - Else Statement


if( mynonprintablechar == 129)
     printf(“You expected me”);
else
     printf(“You may get me”);

Example 2: Switch Statement


switch(mynonprintablechar)
{
    case 129:
        printf(“You expected me”);
        break;
    default:
        printf(“You may get me”);
}

The solution:


1. Have unsigned char as variable type.
2. downcast the int against which you compare to char.
3. cast as unsigned char.

Do drop me a mail, if I saved you from scratching your hair :)
Disclaimer:

The above post and all the posts in the blog are derived from facts, information, logical interpretation and logical conclusion of printed and internet materials available to me, perceived and produced by 99 gm brain of mine, which by no means always be accurate, consistent and complete.

All the posts are for personal quick reference only.

If any suggestion, correction, misinterpretation, misconception commented, which will be moderated and deleted if required, to avoid unforeseen issues.

If any trademark / copywrite issue is present, do send in a mail and appropriate tag (logo, name, website link) will be attached to the same.

Additional disclaimer will be attached wherever required in the post.