0

I have strings like following: i have tried .title() and capitalize() but not successes.

Input

"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"

Output

"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"

I have try this also, but when input string with more then one space then its got error.

str = "Hello   World  Lol"
for i in range(0,len(new)):
    str += new[i][0].upper() + new[i][1:] + " "
print str
Alpesh Valaki
  • 1,611
  • 1
  • 16
  • 36
  • what do you want to do exaclty? – Astrom Apr 18 '17 at 17:03
  • When I do `"hello world".title()` on my machine, I get `"Hello World"`. Is that not what you get? What do you get? You _are_ assigning the result or displaying it, right? Note that strings are immutable, so if you so `s = "hello world"; s.title(); print(s)`, it will still print the uncapitalized version. – Kevin Apr 18 '17 at 17:04
  • Why doesn't `.title()` work? How is it any different? – Nick T Apr 18 '17 at 17:05
  • 2
    Possible duplicate of [How to capitalize the first letter of each word in a string (Python)?](http://stackoverflow.com/questions/1549641/how-to-capitalize-the-first-letter-of-each-word-in-a-string-python) – gyre Apr 18 '17 at 17:05
  • `.title()` work for me also. Not sure why for author it does not. – m0nhawk Apr 18 '17 at 17:05
  • i want to capitalize first character of word without losing space and if first character is number then leave it as it is – Alpesh Valaki Apr 18 '17 at 17:05
  • @m0nhawk with .title() if string is "1hello world" it will capitalize "1Hello World" i dont want to capitalize second character. output should be "1hello World" – Alpesh Valaki Apr 18 '17 at 17:08
  • you can you `capitalize()` method check below answer. – bhansa Apr 18 '17 at 17:11
  • @Bhansa your answer worked! Thanks ! – Alpesh Valaki Apr 18 '17 at 17:13

2 Answers2

3

How have you tried .title()? str.title() should return the capitalised string but bear in mind strings are immutable so you will have to assign it to a new value.

string1 = "hello   world  lol"
string2 = string1.title()
Josh Laird
  • 6,974
  • 7
  • 38
  • 69
1

In your context you can use capitalize() method.

str = "Helo  w world lol"
lista = []
for i in str.split(" "):
    lista.append(i.capitalize())
print " ".join(lista) #"Helo  W World Lol"

Using list comprehension:

print " ".join([i.capitalize() for i in str.split(" ")])
bhansa
  • 7,282
  • 3
  • 30
  • 55