J'ai des chaînes comme suit: j'ai essayé .title () et capitalize () mais pas les succès.
Contribution
"hello world"
"1hello world"
"hello world lol"
"1 2 2 3 4 5 6 7 8 9"
"1 w 2 r 3g"
"132 456 Wq m e"
"q w e r t y u i o p a s d f g h j k l z x c v b n m Q W E R T Y U I O P A S D F G H J K L Z X C V B N M"
Sortie
"Hello World"
"1hello World"
"Hello World Lol"
"1 2 2 3 4 5 6 7 8 9"
"1 W 2 R 3g"
"132 456 Wq M E"
"Q W E R T Y U I O P A S D F G H J K L Z X C V B N M Q W E R T Y U I O P A S D F G H J K L Z X C V B N M"
J'ai essayé ceci aussi, mais quand la chaîne d'entrée a plus qu'un espace alors elle a l'erreur.
str = "Hello World Lol"
for i in range(0,len(new)):
str += new[i][0].upper() + new[i][1:] + " "
print str
Réponses:
1 pour la réponse № 1Dans votre contexte, vous pouvez utiliser capitalize()
méthode.
str = "Helo w world lol"
lista = []
for i in str.split(" "):
lista.append(i.capitalize())
print " ".join(lista) #"Helo W World Lol"
Utilisation de la compréhension de liste:
print " ".join([i.capitalize() for i in str.split(" ")])
3 pour la réponse № 2
Comment as-tu essayé .title()
? str.title()
devrait retourner la chaîne en majuscule, mais gardez à l'esprit que les chaînes sont immuables, vous devrez donc l'attribuer à une nouvelle valeur.
string1 = "hello world lol"
string2 = string1.title()