【问题标题】:How to extract first letters of strings in python? [closed]如何在python中提取字符串的第一个字母? [关闭]
【发布时间】:2021-07-06 06:10:33
【问题描述】:

我是这样做的。我相信还有很多其他方法可以更专业地做到这一点。 不要介意我的代码,我两周前开始使用 python,它是我的第一语言。

"""Grab the first letters of the names:"""
names = 'Schmo', 'Nate', 'Wonderboy'
first_lett = []
first_lett.append(names[0][0])
first_lett.append(names[1][0])
first_lett.append(names[2][0])
print(first_lett)

【问题讨论】:

  • 如果您的代码按预期工作,并且您正在寻找有关改进它的建议,那么您的问题可能会在codereview.stackexchange.com 上更热门

标签: python string append character


【解决方案1】:

欢迎, 另一种方法:

names = 'Schmo', 'Nate', 'Wonderboy'
first_letter = []
for i in names:
    first_letter.append(i[0])
    
print(first_letter)

输出:

['S', 'N', 'W']

【讨论】:

    【解决方案2】:

    欢迎来到蟒蛇!做得很好。使用列表理解的更“pythonic”方式是:

    first_lett = [n[0] for n in names]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-23
      • 1970-01-01
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      相关资源
      最近更新 更多