Normalizing a list of names in Python

后端 未结 1 809
梦毁少年i
梦毁少年i 2021-01-29 16:06

Let\'s say I have a list of names :

names = [\'King ARTHUR\',
         \'Lancelot The brave\',
         \'galahad the  pure\',
         \'Servant  patsy\',
              


        
相关标签:
1条回答
  • 2021-01-29 16:31

    You can use string methods. If you encounter a 'the' in any form, you just put it into lower case. Every other part of the string is assumed to be a name and is capitalized.

    names = list(set([' '.join(i.lower() if i.lower() == 'the' else i.capitalize() for i in name.split())
                      for name in names]))
    

    This uses the join() method to merge the modified parts of the string again and builds a new list based on the names list. To eliminate duplicates, the set function is used, finally the set is converted back to a list.

    0 讨论(0)
提交回复
热议问题