ABSP, Ch 7, Practice Project #2

My solution to the Practice Project #2 in Chapter 7 of the excellent book “Automate the Boring Stuff with Python” (ABSP)

#! usr/bin/env python3
# by lorenzo - 22/07/2017
# regex version of strip() function

import re

def regexStrip(aString, ch = ''):
    if not ch:
        stripRegex = re.compile(r'\S.*\S')
        mo = stripRegex.search(aString)
        noMatch = "the string contains only whitespace!"
        if mo:
            return mo.group()
            return noMatch
        rString = '[^'+ ch + ']+'
        stripRegex = re.compile(rString)
        cleanedString = ''
        for x in stripRegex.findall(aString):
            cleanedString += x
        return cleanedString 

print('Enter a string')
someString = input()
print('Insert a character you want to remove from the previously inserted string (whitespace included)')
removeCharacter = input()
if removeCharacter == ' ':
    print(regexStrip(someString, removeCharacter))

Comments about the code are welcome.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s