如何列出用户在Python中键入的输入字符串?

2024-03-28 18:00:12 发布

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

我是编程新手,在我的脚本中,我必须创建一个带有输入字符串y的列表。你知道吗

我知道切片和制作列表的基本方法ex:list=[]

但我需要编写代码,以便字符串中键入的每个单词都成为列表中的一个集合数字。你知道吗

例如:如果用户打印,你好,我的名字是

列表中必须是hello my name,is hello is=1 my=2 name=3 is=4

那我就得把单子上每个单词的第一个字母都去掉???你知道吗

有人能帮忙吗???你知道吗


Tags: 方法字符串代码name脚本hello列表is
3条回答
In [32]: L = input("Enter a sentence: ").split()
Enter a sentence: Hello my name is

In [33]: L
Out[33]: ['Hello', 'my', 'name', 'is']

In [34]: L[0]
Out[34]: 'Hello'

In [35]: L[1]
Out[35]: 'my'

In [36]: for i in range(len(L)):
   ....:     print(i, L[i])
   ....:     
0 Hello
1 my
2 name
3 is


In [37]: firsts = [i[0] for i in L]

In [38]: firsts
Out[38]: ['H', 'm', 'n', 'i']

如果你需要更多的python风格,基本上和@inspectorg4dget的答案是一样的

>>> first_char = [word[0] for word in raw_input("Enter a sentence : ").split()]
Enter a sentence : Hello my name is
>>> first_char
['H', 'm', 'n', 'i']
>>>

我的理解是,你想得到列表中每个单词的第一个字符

这是一个快速的解决方案。你知道吗

>>> x = 'Hello my name is'
>>> new_list = x.split(' ')
>>> new_list
['Hello', 'my', 'name', 'is']
>>> [i[0] for i in new_list]
['H', 'm', 'n', 'i']
>>> 

相关问题 更多 >