-1

In python, I'm supposed to write a program that asks the user for a string, and then it removes all occurrences of p, q, r, s, t (lower and upper-case), then print out everything else. For input Today it is Tuesday it should print oday i i ueday.

I've written the code but it doesn't remove the last letter if needed. Here is what I've written:

S = str(input("Please enter some text: "))
L = list(S)
for i in L :
     if i in 'tsrqpPQRST' :
         L.remove(i)
string = ""
for char in L :
     string = string + char
print(string)

4 Answers4

1

You could use str.translate.

>>> test = 'Today it is Tuesday'
>>> removeText = 'pqrst'
>>> test.translate(None, removeText+removeText.upper())
'oday i i ueday'

Since you're on Python 3, use the translate() method like this.

>>> test = 'Today it is Tuesday'
>>> removeText = 'pqrst'
>>> test.translate(dict.fromkeys(ord(elem) for elem in removeText+removeText.upper()))
'oday i i ueday'

The problem in your code is that you're removing stuff from the list while iterating over it.

Just doing this works. (Here you make a copy, iterate over it, while removing the element from the original list)

>>> testList = list(test)
>>> for i in testList[:]:
        if i in 'pqrstPQRST':
            testList.remove(i)


>>> "".join(testList)
'oday i i ueday'

P.S - Instead of using string = '' and iterating over the list and joining the characters, just use "".join(...).

Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
1

You can use regular expression:

 import re
 new_string = re.sub('(?i)[pqrst]', '', S)
Michael
  • 15,386
  • 36
  • 94
  • 143
  • +1 - Regex solves this problem quickly and easily. However, you can make it even better: `re.sub('(?i)[p-t]', '', S)`. This works because "pqrst" is in the order of the alphabet. –  Jul 28 '13 at 16:21
1

You can combine join and generator expression. Combine for loop and string concatation is not efficient or pythonic. Also, string itself is iterable, no need to turn it into a list.

>>> s = 'Today it is Tuesday'
>>> ''.join(x for x in s if x not in 'pqrstPQRST')
'oday i i ueday'
>>> 
zhangyangyu
  • 8,520
  • 2
  • 33
  • 43
0

There's a lot of ways to do that. e.g.

>>> s = "helllo"
>>> s.replace("l","")
'heo'
>>> s.translate(None,"le")
'ho'
>>> 

As a side note, you don't have to turn a string into a list to iterate over it but you shouldn't modify an iterable when you iterate over it, so if you would like to improve your code it would be something along the lines of:

>>> s
'helllo'
>>> m = ""
>>> for i in s:
        if i not in "el": #put the list of characters here
                m += i


>>> m
'ho'
>>> 

This way you are making a copy of a string, you don't run into problems that you have when you modify it during iteration.

Pawel Miech
  • 7,742
  • 4
  • 36
  • 57