如何打印仅包含字母的单词列表切片。蟒?但是我错过了什么?

How to print the slice of the list of words that only includes letters. python? But what am i missing?

提问人:Bre JaNa 提问时间:11/19/2021 更新时间:11/19/2021 访问量:679

问:

这是我到目前为止所拥有的:

    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))

我知道我需要在那里的某个地方进行追加和排序。

以下是说明:

  1. 使用 for 循环或内置函数将提供的字符串转换为列表,并将结果存储在新变量中。
  2. 对列表进行排序。
  3. 打印仅包含字母的列表切片。

这是我的答案,我应该是什么样子:

    ['C', 'T', 'T', 'W', 'a', 'e', 'e', 'e', 'e', 'f', 'g', 'h', 'h', 'i', 'l', 'o', 'o', 'r', 'r', 's', 's', 't', 'v']
python 字符串 列表 for 循环 切片

评论

0赞 Michael Butscher 11/19/2021
您不必先“拆分”字符串。看看“list(string)”是做什么的。
0赞 Copperfield 11/19/2021
要获取给定字符串的字符列表,您只需要调用该字符串的 list,例如:list(strVar)
0赞 Copperfield 11/19/2021
指令的 for 循环部分是过滤部分的提示,也就是只保留字母字符,为此,您可以在 for 循环中使用字符串的 .isalpha 方法,也可以使用内置函数filter
0赞 Bre JaNa 11/19/2021
@Copperfield好吧,所以我在这样做时得到了这个:['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
@Copperfield你是怎么做到的呢?

答:

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
我们不喜欢做你的功课......但是,为了获得提示,请尝试查找关键字并查看inif 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 是一个方法形式的字符串,它告诉你字符串是一个字母