【问题标题】:How to make a function shorter如何使函数更短
【发布时间】:2021-11-05 13:31:50
【问题描述】:

我有这个功能,但我试图让它尽可能短。类似于:返回 [result(result += word[0]) for word in text]。基本上是一行,但是好像不行。

def first_letter(text):
    text = text.upper().split()
    result = ''
    for word in text:
        result += word[0]
    return result

【问题讨论】:

    标签: python python-3.x string


    【解决方案1】:
    def first_letter(text):
        return "".join([word[0] for word in text.upper().split()])
    

    【讨论】:

    • join 也适用于生成器。 [] 可以从它的参数中删除。 join(word[0]...) 应该可以工作。
    【解决方案2】:

    使用正则表达式替换可以更短(忽略导入语句)。

    import re
    def first_letter(text):
      return re.sub(r"(\S)\w*\s*", r"\1", text.upper())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多