Home > Software design >  How to print the slice of the list of words that only includes letters. python? But what am i missin
How to print the slice of the list of words that only includes letters. python? But what am i missin

Time:11-19

This is what I have so far:

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

I know I need to have append and sort somewhere in there.

These are the instructions:

  1. Convert the provided string to a list using a for loop or built-in function and store the result in a new variable.
  2. Sort the list.
  3. Print the slice of the list that only includes letters.

This what my answer I supposed to look like:

    ['C', 'T', 'T', 'W', 'a', 'e', 'e', 'e', 'e', 'f', 'g', 'h', 'h', 'i', 'l', 'o', 'o', 'r', 'r', 's', 's', 't', 'v']

CodePudding user response:

Kindly try:

sorted([x for x in 'Together We Thrive, Class of 2025!' if x.isalpha()])

Or, pass the name of the defined variable.

This outputs:

['C',
 'T',
 'T',
 'W',
 'a',
 'e',
 'e',
 'e',
 'e',
 'f',
 'g',
 'h',
 'h',
 'i',
 'l',
 'o',
 'o',
 'r',
 'r',
 's',
 's',
 't',
 'v']

CodePudding user response:

please try this:

strvar = "Together we Thrive, Class of 2025!"

Listt=[ ]

for letter in strvar:
    if (letter.isalpha()):
        Listt.append(letter)

Listt.sort()

print(Listt)
  • Related