Reputation: 4256
trying to make a simple function that'll take a phrase, a letter, and then output the original phrase with that letter removed. I can do the simple version but seem to get my wires crossed when I try to cover both lowercase and uppercase. ( it works fine if i do just 'if i not in aChar)
i.e. If i input 'Board of Trade' and my letter to extract is 'O', i want both the uppercase and the lowercase removed. I'm a beginner so any general tips regarding my code would be much appreciated as well.
Here's my script:
def removal(statement,aChar):
newstring = ''
lowercase = aChar.lower()
uppercase = aChar.upper()
for i in statement:
if i not in aChar or lowercase or uppercase:
newstring = newstring+i
print(newstring)
removal('Board of Trade', 'O')
Upvotes: 0
Views: 2682
Reputation: 13869
This can be done in one line with str.translate()
:
def delchar_ci(s, ch):
return s.translate(None, ch.lower() + ch.upper())
s = 'Board Of Trade'
print delchar_ci(s, 'o') # 'Bard f Trade'
print delchar_ci(s, 'o') == delchar_ci(s, 'O') # True
Upvotes: 0
Reputation: 824
Here is a simple function that replaces the given character with an empty character. It replaces both upper and lower cases of that character. If you just want to replace the character given blindly, use the second answer:
import string
def myfunc(mystr, mychar):
return (mystr.replace(mychar.lower(), "")).replace(mychar.upper(), "")
myfunc("This is test sentence", "t")
Second answer(use the character given blindly):
def myfunc(mystr, mychar):
return mystr.replace(mychar, "")
Upvotes: 0
Reputation: 5696
.replace()
would make your function slightly more readable.
There is also a mistake with this: i not in aChar or lowercase or uppercase
The equivalent of what you wrote is (i not in aChar) or True or True
.. which is always true.
def removal(statement,aChar):
lowercase = aChar.lower()
uppercase = aChar.upper()
newstring = statement.replace(lowercase, '').replace(uppercase, '')
print(newstring)
removal('Board of OTrade', 'O')
Upvotes: 1
Reputation: 82
What you could do is convert the capital O to a lowercase O. Similar to this:
def removal(statement,aChar):
newstring = ''
for i.lower() in statement:
if i != aChar.lower()
newstring += i
print(newstring)
Upvotes: 0
Reputation: 1904
def removal(statement,aChar):
newstring = ''
# look at each character in your statement
for i in statement:
# convert everything to lowercase and make sure they don't match
if i.lower() != aChar.lower():
newstring = newstring + i
return newstring
Upvotes: 3
Reputation: 16711
Change your conditional to test if there is an element in an iterable:
if i not in (aChar, lowercase, uppercase): # you really don't need aChar
Upvotes: 0