在列表中打印单个字母

社会演员多 python 419

原文标题Printing individual letters in a list

我正在编写一个程序,该程序从用户那里获取语句或短语并将其转换为首字母缩略词。

它应该看起来像:

Enter statement here:
> Thank god it's Friday
Acronym : TGIF

我发现完成此操作的最佳方法是通过列表并使用.split()将每个单词分成自己的字符串,并且能够隔离第一项的第一个字母,但是当我尝试通过以下项目修改程序时将打印语句更改为:

print(“首字母缩略词:”, x[0:][0])

它只是最终打印第一项中的全部字母。

这是我到目前为止所得到的,但是它只打印第一个项目的第一个字母……

acroPhrase = str(input("Enter a sentence or phrase : "))     
acroPhrase = acroPhrase.upper()  

x = acroPhrase.split(" ")  
    print("Acronym :", x[0][0])

原文链接:https://stackoverflow.com//questions/71685671/printing-individual-letters-in-a-list

回复

我来回复
  • Tim Biegeleisen的头像
    Tim Biegeleisen 评论

    使用re.sub和回调我们可以尝试:

    inp = "Peas porridge hot"
    output = re.sub(r'(\S)\S*', lambda m: m.group(1).upper(), inp)
    print(output)  # PPH
    
    2年前 0条评论
  • playerJX1的头像
    playerJX1 评论
    acroPhrase = str(input("Enter a sentence or phrase : "))     
    acroPhrase = acroPhrase.upper()  
    
    x = acroPhrase.split(" ")  
    result = ''
    for i in x:
        word = list(i)
        result+=word[0]
    
    print(result)
    
    2年前 0条评论
  • ThatOneAmazingPanda的头像
    ThatOneAmazingPanda 评论

    代码需要遍历.split结果。例如,使用列表推导:

    inp = "Thank god its friday"
    inp = inp.split()
    first_lets = [word[0] for word in inp]
    
    2年前 0条评论