Python 规范化名称列表
我编写此代码是为了规范名称列表:Python 规范化名称列表,python,list,Python,List,我编写此代码是为了规范名称列表: n = ['King ARTHUR', 'Lancelot The brave', 'galahad the pure', 'Servant patsy', 'GALAHAD THE PURE'] for x in n: lw = x.lower() for i in lw.split(): n2.append(i) for i in n2: if i == 'the
n = ['King ARTHUR',
'Lancelot The brave',
'galahad the pure',
'Servant patsy',
'GALAHAD THE PURE']
for x in n:
lw = x.lower()
for i in lw.split():
n2.append(i)
for i in n2:
if i == 'the' :
i.lower()
n3.append(i)
else:
i.capitalize()
n3.append(i)
print(n3)
该守则的目的是消除多余的空格和重复,并使每个骑士姓名和头衔的首字母大写,而“The”是小写。
但是,输出似乎忽略了.capitalize()
命令。
知道缺少什么吗?Python列表的理解有助于:
titles = ['King ARTHUR', 'Lancelot The brave', 'galahad the pure', 'Servant patsy', 'GALAHAD THE PURE']
normalised_titles = [' '.join("the" if w.lower() == 'the' else w.title() for w in title.split()) for title in titles]
print normalised_titles
给你:
['King Arthur', 'Lancelot the Brave', 'Galahad the Pure', 'Servant Patsy', 'Galahad the Pure']
这里的目的是首先使用
split()
生成一个没有任何额外空格的单词列表。对于每个单词,请使用title()
将第一个字符设为大写,除非它是the
,在这种情况下,请将其保持为小写。最后,使用join()
尝试i=i.lower()
和i=i.capitalize()
将所有单词重新连接在一起,每个单词之间留一个空格。这两个函数都不会改变初始值,但会返回它的一个副本:,感谢它的工作,我的问题很愚蠢,我对编程还是新手。不管怎么说,泰克人很多。