python如何将列表,字典,元组,集合首字母变成大写 以及其他的大小写转换!

版权声明:转载请声明原文链接地址,谢谢! https://blog.csdn.net/weixin_42859280/article/details/84675770

我们希望的正常的使用:
下面示例是字符串所以可以使用!

>>> k = 'good blue sky'
>>> k.capitalize()
'Good blue sky'

在这里插入图片描述
报错的是因为你创建的不是字符串,可能是一个列表!
类似这样:

>>> ss = ['mode','in','china']
>>> ss.capitlize()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'capitlize'

在这里插入图片描述

那么就要进行修改啦:

>>> [string.capitalize() for string in ss]
['Mode', 'In', 'China']
>>>

把列表变成sting就行啦!
类似集合,元组,字典都可以!
以下为示例:

>>> d = {'sd','blue'}#集合
>>> d.capitlize()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'set' object has no attribute 'capitlize'
>>> [string.capitalize() for string in d]
['Blue', 'Sd']

>>> c = ('asd','blue')#元组
>>> c.capitalize()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'capitalize'
>>> [string.capitalize() for string in c]
['Asd', 'Blue']
>>>

>>> a = {'abc':'wsd','ews':'edr'}#字典
>>> a.capitalize()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'capitalize'
>>> [string.capitalize() for string in a]
['Abc', 'Ews']
>>>

集合:
在这里插入图片描述元组:
在这里插入图片描述
字典:
只会大写键!
在这里插入图片描述
其他函数类似,都是将其变成string格式再进行调用函数:
其他函数链接:
https://blog.csdn.net/weixin_42859280/article/details/84675684

猜你喜欢

转载自blog.csdn.net/weixin_42859280/article/details/84675770