0

I have to strip anything that isn't a letter between a-z (lowercase only) out of a sentence. I wrote this

def breakPhrase(string):
    string=string.lower()
    for character in string:
        if ord(character) < 97 or ord(character) > 122:
            string=string.strip(character)
    return string

and it works, but only if theres only one punctuation or non alphabetical character. like if I passed "i dont know..." it would only strip out one of the periods, where I need it to strip all of them out. what am I doing wrong?

4
Contributors
5
Replies
13
Views
8 Years
Discussion Span
Last Post by sachin004
0

The strip() function only removes leading and trailing characters:

text = 'goodbye! cruel, harsh world!..?'
print text.strip('!,.?')  # goodbye! cruel, harsh world

To remove characters all through the text you can use a loop this way:

text = 'goodbye! cruel, harsh world!..?!'
stripped_text = ""
for c in text:
    if c in '!,.?':
        c = ""
    stripped_text += c

print stripped_text  # goodbye cruel harsh world
0

Ahh I see, now that you say that I kinda remember reading that about the strip function, well with that I should be able to get this working easily, thank you!

0

Use the string module - it has a built-in for lower-case letters. This is preferable to specifying the ASCII characters - what happens if you run on an EBCDIC system? You're better off seeing if each character is valid, and if it is, appending it to a new string.

0

I'll keep that in mind, I don't think its important for this assignment since it isn't going to be used in any real world application, its just an assignment. But thanks for the info, I'll check it out a later tonight

0
import re
a="what is. your. name?"
b=re.findall(r'\w+',a)
print b
#this program removes all punctuation and prints the final output

Edited by peter_budo: Keep It Clear - Please use code tags

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.