Python:将字符串中除一个单词外的单词的第一个字符大写
我有字符串Python:将字符串中除一个单词外的单词的第一个字符大写,python,python-3.x,string,list-comprehension,Python,Python 3.x,String,List Comprehension,我有字符串a='1346'。变量a总是包含一些文字量。我想大写字符串中每个单词的前几个字符,除了特定的单词和'。以下是我的代码,它正在充分发挥作用: b = [] for i in a.split(): if i.lower() == 'and': b.append(i.lower()) else: b.append(i.capitalize()) aa = " ".join(b) #'Thirteen Thousand and Forty
a='1346'
。变量a
总是包含一些文字量。我想大写字符串中每个单词的前几个字符,除了特定的单词和'
。以下是我的代码,它正在充分发挥作用:
b = []
for i in a.split():
if i.lower() == 'and':
b.append(i.lower())
else:
b.append(i.capitalize())
aa = " ".join(b) #'Thirteen Thousand and Forty Six'
我试过的另一个oneliner是:
aa = " ".join([k.capitalize() for k in a.split() if k.lower() != 'and'])
但是,它返回的结果字符串是'139046'
,省略了单词'和'
问题是,对于这项工作,是否存在使用列表理解或某些内置函数(不使用regex)的OneLiner?正确的语法应该是
aa = " ".join([k.capitalize() if k.lower() != 'and' else k for k in a.split()])
当您将
if
子句放在理解末尾时,它将跳过不满足条件的元素。但是,您的要求是在项目为和“
时逐字返回该项目。正确的语法应该是
aa = " ".join([k.capitalize() if k.lower() != 'and' else k for k in a.split()])
当您将
if
子句放在理解末尾时,它将跳过不满足条件的元素。但是,您的要求是在项目为和“
时逐字返回项目,而不是在默认情况下拆分(split()
)为什么不在“和”上拆分,并使用“和”重新加入
与其在默认情况下拆分(
split()
),为什么不在“and”上拆分,并使用“and”重新连接呢
你可以在资本化后用和替换“And”
a = 'thirteen thousand and forty six'
(' ').join([x.capitalize() for x in a.split(' ')]).replace('And', 'and')
你可以在资本化后用和替换“And”
a = 'thirteen thousand and forty six'
(' ').join([x.capitalize() for x in a.split(' ')]).replace('And', 'and')
以下代码段可能很有用,它只是以单行python代码提供了所需的输出:
s = 'thirteen thousand and forty six'
print(s.title().replace('And', 'and'))
以下代码段可能很有用,它只是以单行python代码提供了所需的输出:
s = 'thirteen thousand and forty six'
print(s.title().replace('And', 'and'))
使用这段代码有一个问题,即使它完成了目的,那就是如果字符串中有任何单引号,比如“十三t'nd和四十六”;它将返回“十三和四十六”,字符紧靠大写单引号。@michaelpetronav感谢您注意到这个错误;为了达到这个目的,我们可以使用s=string.capwords(s,sep='').replace('And','And')。使用这个代码有一个问题,即使它完成了这个目的,那就是如果字符串中有任何单引号,比如“十三t'nd和四十六”;它将返回“十三和四十六”,字符紧靠大写单引号。@michaelpetronav感谢您注意到这个错误;为了达到这个目的,我们可以使用s=string.capwords(s,sep='')。替换('And','And')。