#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    15
    Rep Power
    0

    Create List with Letters Only From User Input


    I am trying to create a list with just letters from user input. I only want letters, no numbers or special characters, and only single letters.

    I have:


    Code:
    letter = input('enter your letters seperated by space: ')
    if letter.isalpha():
        letters = letter.split(' ')
        return letters
    I know that this does not work because a space doesn't fall under ".isalpha()"

    It seems so simple but I'm drawing a blank

    Any thoughts

    Thanks
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Location
    Canada
    Posts
    51
    Rep Power
    2
    Originally Posted by CastorTroy
    I am trying to create a list with just letters from user input. I only want letters, no numbers or special characters, and only single letters.

    I have:


    Code:
    letter = input('enter your letters seperated by space: ')
    if letter.isalpha():
        letters = letter.split(' ')
        return letters
    I know that this does not work because a space doesn't fall under ".isalpha()"

    It seems so simple but I'm drawing a blank

    Any thoughts

    Thanks
    One mistake you made was the return. Return is only or functions and functions need a def statement. Also it is possible to test each character without separating them, most common is the for loop. The code below should work for you.
    Code:
    def letters():
    	word = input('type something ')
    	letter_list = []
    	for letter in word:
    		if letter.isalpha():
    			letter_list.append(letter)
    	return letter_list
    If you want to make the returned list into a string again you can use the join() method.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    15
    Rep Power
    0
    Got it...Thanks for the help, much appreciated
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    76
    Rep Power
    2
    Protip: We can simplify the for loop down by use of a generator encapsulated in list().
    Code:
    def letters():
    	word = input('type something ')
    	return list(letter for letter in word if letter.isalpha())

    Comments on this post

    • Good News agrees : I suppose your 3 lines beats my 7 haha

IMN logo majestic logo threadwatch logo seochat tools logo