Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMousa Alqarni
22,619 Pointshow to remove word in string like common words ( and , or , # , / , low) in pyathon3
how to remove word in string like common words ( and , or , # , / ) in pyathon3 some times words small or cap letter ..
str = "SY-LCP LOW BEND MEDIAL DISTAL TIBIA PLATE 3.5 # 01.112.062"
print (str.split( ))
2 Answers
Chris Freeman
Treehouse Moderator 68,423 PointsUsing str.replace()
requires scanning the entire string for each unique element you wish to replace. This is inefficient for lots of changes.
You can use the regular expression re.sub()
to remove all specific characters in one pass. You can also compare to a "bad word" set. Examples below
It's not a good practice to use python base type str
as variable name. Using "string" instead.
import re
>>> import re
>>>
>>> string = "SY-LCP LOW BEND MEDIAL DISTAL TIBIA PLATE 3.5 # 01.112.062"
>>> string
'SY-LCP LOW BEND MEDIAL DISTAL TIBIA PLATE 3.5 # 01.112.062'
# remove #, (, /
>>> stripped = re.sub(r'[#(/]', "", string)
>>> stripped
'SY-LCP LOW BEND MEDIAL DISTAL TIBIA PLATE 3.5 01.112.062'
# remove words of 3 or less characters
>>> no_small_words = re.sub(r'\b\w{,3}\b', "", string)
>>> no_small_words
'- BEND MEDIAL DISTAL TIBIA PLATE . # ..'
>>> string2 = "This Scat Scan"
# Remove Capitol letters
>>> no_caps = re.sub(r'[A-Z]', "", string2)
>>> no_caps
'his cat can'
>>> bad_word_set = {"TIBIA", "PLATE"}
# add words using `add`
>>> bad_word_set.add("BEND")
>>> no_small_words
'- BEND MEDIAL DISTAL TIBIA PLATE . # ..'
# remove all words in "bad" set
>>> no_bad_words = " ".join([x
... for x in no_small_words.split()
... if x not in bad_word_set])
>>> no_bad_words
'- MEDIAL DISTAL . # ..'
>>>
Steven Parker
229,202 PointsYou can easily modify a string using the "replace" method. For instance, to create a new string from the above example but without the "#" character (or the following space):
newstr = str.replace("# ", "")
For more sophisticated manipulations, you might want to look into the "regular expression" functions. There's a course here for that: Regular Expressions in Python.
Steven Parker
229,202 PointsSteven Parker
229,202 PointsShowoff!   +1
Chris Freeman
Treehouse Moderator 68,423 PointsChris Freeman
Treehouse Moderator 68,423 Points😊