函数,在Python中打印时不使用大写字母

2024-04-29 19:46:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个简单的函数,它接受一个字符串并返回一个没有原始字符串中大写字母的字符串。我看了很多其他帖子,都有类似的问题,但大多数帖子都是在技巧层面上进行的,由于缺乏知识,我还无法理解

这就是我想到的

def no_capitals(string):
    result = []
    for char in string:
        if not char.isupper(): result.append(char)
    return (result)

print(no_capitals("X007XK"))
print(no_capitals("Xmen R cute"))

这方面的预期输出为:

007
men cute

然而,这个函数毫不奇怪地以列表的形式返回它

['0', '0', '7'] 
['m', 'e', 'n', 'c', 'u', 't, 'e']

所以我猜我必须用另一种方式来处理这个问题。我对Python的了解非常有限,所以我没有很多“工具”可以使用。谁能给我指一下正确的方向吗


Tags: 函数no字符串forcute技巧stringdef
3条回答

最简单的方法是使用+=而不是append。如果使用append,则将字符添加到列表中,而不将结果与下一个字符连接,并在结果中返回带有字符的列表

def no_capitals(string):
    result = ""
    for char in string:
        if not char.isupper(): result += char
    return (result)

print(no_capitals("X007XK"))
print(no_capitals("Xmen R cute"))

更有效的可能性是使用.join()函数。看看下面

def no_capitals(string):
    result = []
    for char in string:
        if not char.isupper(): result.append(char)
    return "".join(result)

print(no_capitals("X007XK"))
print(no_capitals("Xmen R cute"))

保留您创建的结构并仅更改最少的代码量,您可以执行以下操作:

def no_capitals(string):
    #result as a string
    result = ''
    for char in string:
        #if the character is not uppercase add it to the end of result
        if not char.isupper(): result += char
    return (result)

print(no_capitals("X007XK"))
print(no_capitals("Xmen R cute"))

现在给出:

007
men  cute

注意:在男人和可爱之间有两个空格

您可以使用''.join()

def no_capitals(string):
    return ''.join(char for char in string if not char.isupper())


print(no_capitals("X007XK"))
print(no_capitals("Xmen R cute"))

输出:

007
men  cute

相关问题 更多 >