-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

4 回答 4

1

您可以使用正则表达式:

 import re
 new_string = re.sub('(?i)[pqrst]', '', S)
于 2013-07-28T15:53:08.860 回答
1

您可以组合join生成器表达式。结合 for 循环和字符串连接不是有效的或 Pythonic。此外,字符串本身是可迭代的,无需将其转换为列表。

>>> s = 'Today it is Tuesday'
>>> ''.join(x for x in s if x not in 'pqrstPQRST')
'oday i i ueday'
>>> 
于 2013-07-28T15:53:51.107 回答
1

你可以使用str.translate.

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

由于您使用的是 Python 3,因此请使用这样的translate()方法。

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

您的代码中的问题是您在迭代列表时要从列表中删除内容。

只要这样做就行了。(在这里你制作一个副本,迭代它,同时从原始列表中删除元素)

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


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

PS - 而不是使用string = ''和迭代列表并加入字符,只需使用"".join(...).

于 2013-07-28T15:52:24.607 回答
0

有很多方法可以做到这一点。例如

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

作为旁注,您不必将字符串转换为列表来对其进行迭代,但是当您对其进行迭代时,您不应该修改可迭代对象,因此如果您想改进您的代码,这将是沿着行:

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


>>> m
'ho'
>>> 

通过这种方式,您正在制作字符串的副本,您不会遇到在迭代期间修改它时遇到的问题。

于 2013-07-28T15:52:57.797 回答