Python 对列表中的字符串首字母大写处理

时间:2022-07-22
本文章向大家介绍Python 对列表中的字符串首字母大写处理,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

问题描述

有一列表 ['sDe', 'abc', 'SDF'] 问如何将该列表中的字符串全部做首字母大写处理并输出?

示例

输入:

['sDe', 'abc', 'SDF']

输出:

['Sde', 'Abc', 'Sdf']

解法一

使用 map 函数,高阶函数。

并使用 Lambda 函数作为高阶函数的参数。

lt = ['sDe', 'abc', 'SDF']
mp = list(map(lambda x: x[0].upper() + x[1:].lower(), lt))  # map函数
print(mp)

map 函数的定义为:

map(func, *iterables) --> map object

Make an iterator that computes the function using arguments from 
each of the iterables.  Stops when the shortest iterable is exhausted.

第一个参数是一个函数,第二个参数是一个可变长参数。

翻译一下就是说创建一个迭代器,该迭代器使用每个可迭代对象的参数来计算函数。当最短的迭代次数用尽时停止。

在本例中就是说使用迭代访问 lt ,将每个迭代对象作为前面函数的调用参数返回。

解法二

使用列表推导式 + capitalize 方法:

lt = ['sDe', 'abc', 'SDF']
result = [i.capitalize() for i in lt]  # 列表推导式
print(result)

查看函数的源码:

def capitalize(self): # real signature unknown; restored from __doc__
        """
        S.capitalize() -> str
        
        Return a capitalized version of S, i.e. make the first character
        have upper case and the rest lower case.
        """
        return ""

翻译一下就是将首字母大写返回,刚好满足我们的要求。

解法三

使用列表推导式 + title 方法:

lt = ['sDe', 'abc', 'SDF']
result = [i.title() for i in lt]
print(result)

查看函数的源码:

def title(self): # real signature unknown; restored from __doc__
        """
        S.title() -> str
        
        Return a titlecased version of S, i.e. words start with title case
        characters, all remaining cased characters have lower case.
        """
        return ""

翻译一下就是返回起点的那个字符为大写,其余小写。

解法四

这种方法其实就是列表先转字符串,逐个处理之后再拼装成列表;

lt = ['sDe', 'abc', 'SDF']
result = ' '.join(lt).title().split()  # 字符串分割处理
print(result)

查看 join 函数的源码:

def join(self, iterable): # real signature unknown; restored from __doc__
        """
        S.join(iterable) -> str
        
        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
        """
        return ""

翻译一下就是:在 iterable 的字符串中间插入 S;

这里的 iterable 就是 lt ,列表,这里的 S 就是 空格;

所以我们这里的操作其实是将列表拆成字符串然后以空格隔开。