开发者

Iterate python list and capitalize specific letters

开发者 https://www.devze.com 2023-04-10 07:19 出处:网络
I have a list in python, which I\'d like to iterate and capitalize every letter that isn\'t \'A\', s开发者_如何转开发o turn this list:

I have a list in python, which I'd like to iterate and capitalize every letter that isn't 'A', s开发者_如何转开发o turn this list:

['albert', 'angela', 'leo', 'bridget']

Into:

['aLBERT', 'aNGELa', 'LEO', 'BRIDGET']


[''.join(c.upper() if c != 'a' else c for c in word) for word in the_list]


All of the existing answers seem to want to operate on the characters individually. It is simpler and easier just to handle the words as a whole:

>>> the_list = ['albert', 'angela', 'leo', 'bridget']
>>> [ word.upper().replace('A', 'a') for word in the_list]
['aLBERT', 'aNGELa', 'LEO', 'BRIDGET']


This is what str.translate is for:

import string

table = string.maketrans(string.ascii_lowercase.replace('a', ''),
                            string.ascii_uppercase.replace('A', ''))

names = ['albert', 'angela', 'leo', 'bridget']

print [name.translate(table) for name in names]

translate takes a 256 character table, so you use string.maketrans to turn the string constants representing the lowercase and uppercase alphabet into a table. Any letters not appearing in the table are ignored, so removing a and A will uppercase all other letters.

Then just apply the translation table to each name in the list.

It will be faster than iterating over each name and calling upper on every letter but a. While the general Python tools make this easy, this is the tool specifically made for this job.


>>> import re
>>> sl = ['albert', 'angela', 'leo', 'bridget']
>>> [re.sub('[^a]+', lambda m: m.group(0).upper(), s) for s in sl]
['aLBERT', 'aNGELa', 'LEO', 'BRIDGET']


The inelegant way is simple

  lst = ['albert', 'angela', 'leo', 'bridget']
  lst2 = []

  for wrd in lst:
      newwrd = ''
      for ltr in wrd:
          if ltr != 'a':
              newwrd += ltr.upper()
          else: newwrd += ltr
      lst2.append(newwrd)

However list complrehensions will be more pythonic

lst = ['albert', 'angela', 'leo', 'bridget']
[''.join(ltr.upper() if ltr != 'a' else 'a' for ltr in wrd) for wrd in lst]

This is essentially nested list comprehensions replacing the nested loops. This is a much neater solution and more understandable

A list comprehension is an expression (ltr.upper() if ltr == 'a') followed by "for" and then option if clauses. Here we have two (and I see @JBernardo did the same thing) acting in same way as nested for loops.

I hope that helps explain the differences.


If you want to engage the functional programming paradigm a bit more:

def maybe_upper(c, u):
    return c.upper() if c in u else c

def some_upper(s, u):
    return ''.join(map(lambda c: maybe_upper(c, u), s))

>>> some_upper("wahwahweeeewagh", 'uea')
'wAhwAhwEEEEwAgh'
0

精彩评论

暂无评论...
验证码 换一张
取 消