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?

Recommended Answers

All 5 Replies

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

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!

Member Avatar for kdoiron

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.

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

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.