首页 > 解决方案 > 如何访问for循环中的下一个值

问题描述

所以我试图在一个句子中获取单词的第一个字母(不包括第一个单词,我已经解决了这个问题)。

但它会在列表中附加空格。

如果您能提供帮助将不胜感激。

这是代码:

lst = []

for t in (input()):
    if t == " ":
     lst.append(t)

print(*lst, sep="")

输入1:asd dfd yjs

输出1:dy

标签: python

解决方案


只是这个:

''.join([s[0] for s in input().split()[1:]])

一步步:

如果input()返回asd dfd yjs

拆分字符串(更多):

input().split() # output: ['asd', 'dfd', 'yjs']

子列表(更多):

input().split()[1:] # output: ['dfd', 'yjs']

一行循环(更多):

[s[0] for s in ['dfd', 'yjs']] # output: ['d', 'y']

子字符串(更多):

s="dfd"
s[0] # output: d

concat 字符串列表(更多):

''.join(['d', 'y']) # output: dy

推荐阅读