假设我有一个名字和姓氏字符串,例如,可以由两个姓氏组成:

brian molko-olsdal stefan olsdal-molko

我需要拆分姓氏,但是,我需要将后一个大写字母大写,但是我需要将“-”号保持在适当的位置。现在,我有这样的事情:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

if __name__ == "__main__":


    def normalize(name, sign) :

        tmplist = []

        if name.find(sign) != -1 :
            tmp = name.split(sign)
            for t in tmp :
                t.lower()
            for t in tmp :
                t = t[0].upper() + t[1:]
                tmplist.append(t)

        return ' '.join(tmplist)

    n1 = 'brian molko-olsdal stefan olsdal-molko'

    print normalize(n1, '-')
    print normalize(n1, ' ')


结果字符串应如下所示:Brian Molko-Olsdal Stefan Olsdal-Molko

最佳答案

只需使用name.title()

In [166]: name = 'brian molko-olsdal stefan olsdal-molko'
In [168]: name.title()
Out[168]: 'Brian Molko-Olsdal Stefan Olsdal-Molko'

10-06 00:39