创建只产生字符串首字母的函数

2024-05-16 20:34:11 发布

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

在尝试找出输出“短语”首字母的函数时遇到一些困难。这就是我目前所拥有的。谢谢你的帮助

def initials(phrase):
    words = phase.split
    result = ""

    for word in words:
        result += 1
    return result

print(initials("United Nations"))           # Should be: UN
print(initials("United States of America")) # Should be: USOA
print(initials("Banana Boat")).              # Should be: BB

Tags: 函数fordefberesultwordunitedsplit
3条回答

尽量遵循采购订单的逻辑,不要对结构进行额外更改。只需修复错误:

def initials(phrase):
    #words = phase.split()
    result = ""

    for word in phrase.split():   # break the words
        result += word[0]         # get the first letter of each word
    return result

print(initials("United Nations"))           # Should be: UN
print(initials("United States of America")) # Should be: USOA

可能有更多的python方法可以达到同样的效果,但这里试着回答PO的问题

或者只使用一个衬套,使用如下发电机:

phrase = 'United Nations'
inits = ''.join(w[0] for w in phrase.split())'  # `UN`

字符串只是一个字符数组,在Python中,您只需访问字符串中的第一个位置AKA[0]:

def initials(phrase):
  words = phase.split()
  result = ""
    for word in words:
        result += word[0]
    return result

如果您想要全部大写,只需在“word[0]”中使用.upper()

嗯,aword的首字母是word[0],但是你想大写,所以就去吧

def initials(phrase):
    return ''.join(word[0].upper() for word in phrase.split())

相关问题 更多 >