2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > Python 对列表中的字符串首字母大写处理

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

时间:2021-12-04 06:29:09

相关推荐

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 objectMake 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() -> strReturn a capitalized version of S, i.e. make the first characterhave 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() -> strReturn a titlecased version of S, i.e. words start with title casecharacters, 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) -> strReturn a string which is the concatenation of the strings in theiterable. The separator between elements is S."""return ""

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

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

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。