Reputation: 2593
This is my second week of learning python and I got an homework assignment which I have already finished. The thing is that one of the first stages was to take a string and delete all non letters from it (such as "," "." ";", spaces, etc..) so I took the string and each time wrote:
str1 = str.replace(',', '')
str2 = str.replace(' ', '')
....
and so on like 5 times. My teacher says it's fine for now. But it doesn't look good for me. There must be a better way instead of duplicating the code. Can someone explain a better way of doing that?
(I tought about using an ascii function in a condition but couldn't figure it out)
Upvotes: 0
Views: 152
Reputation: 725
>>> s = 'pepito;.:123jdjd'
>>> import string
>>> s.translate(string.maketrans('',''), string.punctuation)
'pepito123jdjd'
Upvotes: 0
Reputation: 51745
one line with out regular expressions and without imports:
''.join( [ x for x in str if x.isalpha() ] )
sample:
>>> ''.join( [ x for x in 'pepito;.:123jdjd' if x.isalpha() ] )
'pepitojdjd'
Upvotes: 0
Reputation: 10553
I will not give you any code as this is a homework assignment, and it'll be better for you if you try coding it yourself. But I'll try to give you some hints to nudge you in the right direction.
As a homework assignment, your teacher expects you to write code that is extensible and manageable. When you duplicate code, it loses both those properties.
For this assignment, the first thing you'd want to do is carefully look at the requirements. There are too many non-alpha characters, so instead of removing each of them, you can consider only including the alpha characters. This can be done using a for
loop.
Once you learn more advanced techniques, you can start researching regex patterns, and using those. In python, those can be found in the re
module.
Upvotes: 1
Reputation: 54312
It's easier to find letters than non-letters:
import string
def clean_string(input_string):
result = ""
for char in input_string:
if char in string.letters: # string.letters contains a...zA...Z
result += char
return result
There are also fancier ways of doing this:
def clean_string2(input_string):
return "".join([char for char in input_string if char in string.letters])
Upvotes: 1
Reputation: 15722
Of course! You can use a loop:
toBeReplaced = [',',' ', ... some more chars ...]
for c in toBeReplaced:
yourString = yourString.replace(c,'')
You might also have a look at regular expressions, which would make your job simpler and more stable. But that's probably not what your teacher want's to see.
Upvotes: 1