提问人:Bre JaNa 提问时间:11/19/2021 更新时间:11/19/2021 访问量:679
如何打印仅包含字母的单词列表切片。蟒?但是我错过了什么?
How to print the slice of the list of words that only includes letters. python? But what am i missing?
问:
这是我到目前为止所拥有的:
strVar = 'Together We Thrive, Class of 2025!'
def stringToList(string):
listRes = list(string.split(" "))
return listRes
strVar = 'Together We Thrive, Class of 2025!'
strVarList = print(stringToList(strVar))
我知道我需要在那里的某个地方进行追加和排序。
以下是说明:
- 使用 for 循环或内置函数将提供的字符串转换为列表,并将结果存储在新变量中。
- 对列表进行排序。
- 打印仅包含字母的列表切片。
这是我的答案,我应该是什么样子:
['C', 'T', 'T', 'W', 'a', 'e', 'e', 'e', 'e', 'f', 'g', 'h', 'h', 'i', 'l', 'o', 'o', 'r', 'r', 's', 's', 't', 'v']
答:
2赞
Celius Stingher
11/19/2021
#1
请尝试:
sorted([x for x in 'Together We Thrive, Class of 2025!' if x.isalpha()])
或者,传递已定义变量的名称。
这将输出:
['C',
'T',
'T',
'W',
'a',
'e',
'e',
'e',
'e',
'f',
'g',
'h',
'h',
'i',
'l',
'o',
'o',
'r',
'r',
's',
's',
't',
'v']
评论
0赞
Bre JaNa
11/19/2021
我们还没有使用isalpha,所以我不能@CelsiusStingher使用它
2赞
VoNWooDSoN
11/19/2021
我们不喜欢做你的功课......但是,为了获得提示,请尝试查找关键字并查看in
if x in USER_DEFINED_STRING
0赞
Celius Stingher
11/19/2021
谢谢@VoNWooDSoN。我同意,我正在尝试通过提供一种在给定输入数据的情况下达到预期输出的方法来帮助您解决问题。不解决家庭作业。
0赞
Alberto Cervantes
11/19/2021
#2
请试试这个:
strvar = "Together we Thrive, Class of 2025!"
Listt=[ ]
for letter in strvar:
if (letter.isalpha()):
Listt.append(letter)
Listt.sort()
print(Listt)
评论
0赞
Bre JaNa
11/19/2021
什么是isalpha?
1赞
Copperfield
11/19/2021
@BreJaNa str.isalpha 是一个方法形式的字符串,它告诉你字符串是一个字母
评论
list(strVar)
filter
['C', 'T', 'T', 'W', 'a', 'e', 'e', 'e', 'e', 'f', 'g', 'h', 'h', 'i', 'l', 'o', 'o', 'r', 'r', 's', 's', 't', 'v']