用Python返回整个字符串;不删除

时间:2018-09-05 11:45:24

标签: python string function

我是Python的初学者,我想从字符串中删除所有大写数字。我试过下面的代码,但是在每次函数调用后都得到None。我应该从该函数返回什么?

def remove_capitals(a_string):
    for latter in a_string:

        if not (ord(latter) in range(65,91)):
            print(latter,end="")
        else:
            continue

print(remove_capitals("A1B2C3D"))
print(remove_capitals("Georgia Institute of Technology"))

我低于输出

123None
eorgia nstitute of echnologyNone

2 个答案:

答案 0 :(得分:2)

您可以使用str.join中的生成器表达式删除string.ascii_uppercase中枚举的所有大写字母

from string import ascii_uppercase
def remove_capitals(a_string):
    return ''.join(i for i in a_string if i not in ascii_uppercase)

>>> print(remove_capitals("A1B2C3D"))
123
>>> print(remove_capitals("Georgia Institute of Technology"))
eorgia nstitute of echnology

答案 1 :(得分:1)

使用isupper

def remove_upper_case(x):
        return ''.join(i for i in x if not i.isupper())

执行:

In [281]: remove_upper_case("Georgia Institute of Technology")
Out[281]: 'eorgia nstitute of echnology'

In [282]: remove_upper_case("A1B2C3D")
Out[282]: '123'