所以我试图得到一个句子中单词的第一个字母(不包括第一个单词,我已经解决了这个问题)。
但它会将空格附加到列表中。
如果你能帮忙我会很感激的。
代码如下:
lst = []
for t in (input()):
if t == " ":
lst.append(t)
print(*lst, sep="")input1:asd dfd yjs
output1:dy
发布于 2021-10-21 17:22:10
就是这样:
''.join([s[0] for s in input().split()[1:]])分步执行:
如果input()返回asd dfd yjs
拆分字符串(more):
input().split() # output: ['asd', 'dfd', 'yjs']子列表(more):
input().split()[1:] # output: ['dfd', 'yjs']单行循环(more):
[s[0] for s in ['dfd', 'yjs']] # output: ['d', 'y']子字符串(more):
s="dfd"
s[0] # output: d字符串串接列表(more):
''.join(['d', 'y']) # output: dy发布于 2021-10-21 17:20:28
你可以
使用切片将句子拆分成单词(从索引1到结尾),然后只保留每个单词的第一个字符,并将其连接到结果字符串x.split()
x = input(">")
result = ""
for word in x.split()[1:]:
result += word[0]
print(result) # dy使用生成器和str.join:
x = input(">")
result = ''.join(word[0] for word in x.split()[1:])发布于 2021-10-21 17:29:43
你得到了空间,因为这是你所要求的。大声朗读你的代码,它可能会有意义:
if t == " ":
lst.append(t)如果t是一个空格,则将其附加到lst
看起来很清楚,你只能得到空格。
您希望追加t后面的字符。使用for循环方法有两种方法可以做到这一点: 1)如果t是一个空格,则追加下一个字符;2)如果前一个字符是空格,则追加t。下面是你可以如何实现#2:
lst = []
prev_char = None
for t in (input()):
if prev_char == " ":
lst.append(t)
prev_char = t
print(*lst, sep="")这将打印除第一个单词之外的每个单词的第一个字符。将last_char初始化为包含第一个单词的空格。
https://stackoverflow.com/questions/69666174
复制相似问题