User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 456,533 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,886 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser: Programming Forums
Views: 1123 | Replies: 11
Reply
Join Date: May 2007
Posts: 268
Reputation: BearofNH is on a distinguished road 
Rep Power: 2
Solved Threads: 19
BearofNH's Avatar
BearofNH BearofNH is offline Offline
Posting Whiz in Training

Tutorial Re: Working with lists

  #11  
Oct 11th, 2007
Originally Posted by MrShoot View Post
(...)Now let me complicate this a bit more. What if I only want to lowercase all the letters but the first letter from each string included in the list? For example, we have:
  1. list = ["CAnADA", "hELLO", "CAN"]
I want it to show up like:
["Canada", "hello", "Can"]

I recommend avoiding using variable names like list as it can get very confusing. Anyhow, a list comprehension could help here:
  1. mylist = ["CAnADA", "hELLO", "CAN"]
  2. newlist = [ x[0]+x[1:].lower() for x in mylist ]
  3. print newlist
['Canada', 'hello', 'Can']

Things get a bit hairer if you allow empty strings in mylist, but that's an exercise for the reader.
Reply With Quote  
Join Date: Aug 2005
Posts: 1,196
Reputation: Ene Uran is on a distinguished road 
Rep Power: 6
Solved Threads: 67
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Veteran Poster

Re: Working with lists

  #12  
Oct 11th, 2007
If you have empty strings in the list you can change BearofNH's code simply:
  1. mylist = ["CAnADA", "hELLO", "", "CAN"]
  2. # use list comprehension
  3. newlist = [ x[0]+x[1:].lower() for x in mylist if x ]
  4. print newlist
  5. """
  6. my output -->
  7. ['Canada', 'hello', 'Can']
  8.  
  9. a list comprehension is a more efficient way of coding this ...
  10. newlist =[]
  11. for x in mylist:
  12. if x != "":
  13. newlist.append(x[0]+x[1:].lower())
  14. """
drink her pretty
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

DaniWeb Python Marketplace
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

Thread Tools Display Modes

Similar Threads
Other Threads in the Python Forum

All times are GMT -4. The time now is 4:36 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC