如何分离字符串中每个单词的第一个字符?

2024-05-13 20:00:05 发布

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

我写了这个程序,但它不起作用,因为,当我输入两个用空格隔开的单词时,我不知道它在做什么

sinput = input("Enter a sentence") #Collects a string from the user
x = len(sinput) #Calculates how many characters there are in the string


for n in range(x):
    n = 0 #Sets n to 0
    lsinput = sinput.split(" ") #Splits sinput into seperate words
    lsinput = lsinput[n] #Targets the nth word and isolates it into the variable lsinput
    print(lsinput[1]) #Prints the 1st letter of lsinput
    n += 1 #Adds 1 to n so the loop can move on to the next word

Tags: thetoin程序inputstring单词sentence
3条回答

我建议从一本关于python的初学者书籍开始。不知道是什么。但一定要读点书。在

为了回答您的问题以帮助您继续工作,您可以这样做:

[w[0] for w in sinput.split() if w]

问题是你:

  • 在每个循环中将n设置回0
  • 你循环了错误数量的迭代
  • 使用1检索第一个字母而不是0(索引从0开始)

根据您的代码调整此项:

sinput = input("Enter a string to convert to phonetic alphabet") #Collects a string from the user

lsinput = sinput.split(" ") #Splits sinput into seperate words
x = len(lsinput) #Calculates how many characters there are in the string

n = 0 #Sets n to 0

for n in range(x):
    print(lsinput[n][0]) #Prints the 1st letter of the nth word in 5lsinput
    n += 1 #Adds 1 to n so the loop can move on to the next word

我还向前移动了lsinput,这样就不会每次迭代都重新计算这个列表。在

我不确定我真的理解这个问题,但如果你想得到输入中每个单词的所有首字母,这个代码就可以了

map(lambda x: x[0], sinput.split(" "))

相关问题 更多 >