By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,715 Members | 748 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,715 IT Pros & Developers. It's quick & easy.

How to write a function to remove digits from a str

P: 31
Given a string consisting of letters and digits only, return a list whose elements are those substrings of the given string that consist of consecutive letters only. For example, alpha("1up2down33sideways77") will return the list ["up", "down", "sideways"].

All i know is that i would have to use s.split()..i think?

any help would be appreciated. thanks.
Feb 7 '09 #1
Share this Question
Share on Google+
4 Replies


boxfish
Expert 100+
P: 469
I haven't seen any built in string functions that look like they could do this for you, although isalpha() could be useful. myString.isalpha() returns true if all the characters in myString are letters. You'll probably have to loop through each character in the string, put it in your list if it's a letter, and append a new string to your list if you find the beginning of a new word.
I hope this gives you some idea of how to solve the problem.
Feb 7 '09 #2

bvdet
Expert Mod 2.5K+
P: 2,851
re.split() should work well for this task.
Expand|Select|Wrap|Line Numbers
  1. >>> import re
  2. >>> re.split('[0-9]', '1up2down33sideways77')
  3. ['', 'up', 'down', '', 'sideways', '', '']
  4. # eliminate null strings with a list comprehension
  5. >>> [item for item in re.split('[0-9]', '1up2down33sideways77') if item]
  6. ['up', 'down', 'sideways']
  7. >>> 
Feb 9 '09 #3

boxfish
Expert 100+
P: 469
Wow, bvdet. Looks like I'd better read up on the re module.
Feb 9 '09 #4

bvdet
Expert Mod 2.5K+
P: 2,851
The re module is very powerful, but it can be cryptic and difficult. Here's a good tutorial: click here

Here's another, not so succinct method of achieving the same result:
Expand|Select|Wrap|Line Numbers
  1. aStr = "1up2down33sideways77"
  2.  
  3. # create a list of indices of the digits in aStr
  4. idxList = [i for i, s in enumerate(aStr) if s.isdigit()]
  5. print idxList
  6. strList = [aStr[idxList[i]+1:idxList[i+1]] for i in range(len(idxList)-1)]
  7. # this list will contain null strings
  8. print strList
  9.  
  10. # similar to the list comprehension above, eliminates null strings
  11. strList2 = []
  12. for i in range(len(idxList)-1):
  13.     s = aStr[idxList[i]+1:idxList[i+1]]
  14.     if s:
  15.         strList2.append(s)
  16.  
  17. print strList2
Feb 9 '09 #5

Post your reply

Sign in to post your reply or Sign up for a free account.