python capitalizar solo la primera letra


Soy consciente .capitalize () pone en mayúscula la primera letra de una cadena, pero ¿qué pasa si el primer carácter es un entero?

Esto

1bob
5sandy

A esto

1Bob
5Sandy
Author: smci, 2012-09-13

8 answers

Si el primer carácter es un entero, no pondrá en mayúscula la primera letra.

>>> '2s'.capitalize()
'2s'

Si desea la funcionalidad, quite los dígitos, puede usar '2'.isdigit() para verificar cada carácter.

>>> s = '123sa'
>>> for i, c in enumerate(s):
...     if not c.isdigit():
...         break
... 
>>> s[:i] + s[i:].capitalize()
'123Sa'
 188
Author: Ali Afshar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-13 15:56:40

Solo porque nadie más lo ha mencionado:

>>> 'bob'.title()
'Bob'
>>> 'sandy'.title()
'Sandy'
>>> '1bob'.title()
'1Bob'
>>> '1sandy'.title()
'1Sandy'

Sin embargo, esto también daría

>>> '1bob sandy'.title()
'1Bob Sandy'
>>> '1JoeBob'.title()
'1Joebob'

Es decir, no solo pone en mayúscula el primer carácter alfabético. Pero entonces .capitalize() tiene el mismo problema, al menos en eso 'joe Bob'.capitalize() == 'Joe bob', así que meh.

 202
Author: DSM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-13 16:18:06

Esto es similar a la respuesta de @Anon en que mantiene el resto del caso de la cadena intacto, sin la necesidad del módulo re.

def sliceindex(x):
    i = 0
    for c in x:
        if c.isalpha():
            i = i + 1
            return i
        i = i + 1

def upperfirst(x):
    i = sliceindex(x)
    return x[:i].upper() + x[i:]

x = '0thisIsCamelCase'

y = upperfirst(x)

print(y)
# 0ThisIsCamelCase

Como @Xan señaló, la función podría usar más comprobación de errores (como verificar que x es una secuencia, sin embargo, omito casos extremos para ilustrar la técnica)

Actualizado por @normanius comentario (gracias!)

Gracias a @GeoStoneMarten en señalar que no respondí a la pregunta! -fijo que

 32
Author: pinkwerks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-26 17:08:32

Aquí hay una línea que pondrá en mayúscula la primera letra y dejará el caso de todas las letras posteriores:

import re

key = 'wordsWithOtherUppercaseLetters'
key = re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), key, 1)
print key

Esto resultará en WordsWithOtherUppercaseLetters

 10
Author: Anon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-22 21:26:39

Al ver aquí contestado por Chen Houwu, es posible usar el paquete string:

import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"
 2
Author: Fábio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:20

Se me ocurrió esto:

import re

regex = re.compile("[A-Za-z]") # find a alpha
str = "1st str"
s = regex.search(str).group() # find the first alpha
str = str.replace(s, s.upper(), 1) # replace only 1 instance
print str
 0
Author: Prasanth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-13 16:06:03

Puede reemplazar la primera letra (preceded by a digit) de cada palabra usando expresiones regulares:

re.sub(r'(\d\w)', lambda w: w.group().upper(), '1bob 5sandy')

output:
 1Bob 5Sandy
 0
Author: WaKo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-16 11:25:33

Una sola línea: ' '.join(sub[:1].upper() + sub[1:] for sub in text.split(' '))

 0
Author: Gürol Canbek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-29 21:19:52