如果第一个字符不是字母,则首字母大写首字母串? [重复]

时间:2022-12-06 19:35:47

This question already has an answer here:

这个问题在这里已有答案:

I'd like to capitalize the first letter in a string. The string will be a hash (and therefore mostly numbers), so string.title() won't work, because a string like 85033ba6c would be changed to 85033Ba6C, not 85033Ba6c, because the number seperates words, confusing title(). I'd like to capitalize the first letter of a string, no matter how far into the string the letter is. Is there a function for this?

我想把字符串中的第一个字母大写。字符串将是一个哈希(因此主要是数字),因此string.title()将不起作用,因为像85033ba6c这样的字符串将更改为85033Ba6C,而不是85033Ba6c,因为该数字会分隔单词,令title()混乱。我想把字符串的第一个字母大写,无论字母到字符串有多远。这有功能吗?

2 个解决方案

#1


10  

Using re.sub with count:

使用带有计数的re.sub:

>>> strs = '85033ba6c'
>>> re.sub(r'[A-Za-z]',lambda m:m.group(0).upper(),strs,1)
'85033Ba6c'

#2


6  

It is assumed in this answer that there is at least one character in the string where isalpha will return True (otherwise, this raises StopIteration)

在这个答案中假设字符串中至少有一个字符,其中isalpha将返回True(否则,这会引发StopIteration)

i,letter = next(x for x in enumerate(myhash) if x[1].isalpha())
new_string = ''.join((myhash[:i],letter.upper(),myhash[i+1:]))

Here, I pick out the character (and index) of the first alpha character in the string. I turn that character into an uppercase character and I join the rest of the string with it.

在这里,我挑选出字符串中第一个字母字符的字符(和索引)。我将该字符转换为大写字符,然后将其加入字符串的其余部分。

#1


10  

Using re.sub with count:

使用带有计数的re.sub:

>>> strs = '85033ba6c'
>>> re.sub(r'[A-Za-z]',lambda m:m.group(0).upper(),strs,1)
'85033Ba6c'

#2


6  

It is assumed in this answer that there is at least one character in the string where isalpha will return True (otherwise, this raises StopIteration)

在这个答案中假设字符串中至少有一个字符,其中isalpha将返回True(否则,这会引发StopIteration)

i,letter = next(x for x in enumerate(myhash) if x[1].isalpha())
new_string = ''.join((myhash[:i],letter.upper(),myhash[i+1:]))

Here, I pick out the character (and index) of the first alpha character in the string. I turn that character into an uppercase character and I join the rest of the string with it.

在这里,我挑选出字符串中第一个字母字符的字符(和索引)。我将该字符转换为大写字符,然后将其加入字符串的其余部分。