I'm really frustrated how the for loop works. Ill post two scenarios. My output should be "12 abc"-->"12 Abc" and if "12abc"-->"12abc"(output). But I came up with two solutions for this:
s= '12 abc'
a_string = s.split()
for word in a_string:
print(" ".join(word.capitalize()))
If i use this for loop I'm getting output as "1 2 A b c"
*Another solution print(' '.join(word.capitalize() for word in a_string))
If I use this for loop I'm getting the correct solution as "12 Abc"
But,
for word in a_string:
print("".join(word.capitalize()),end=' ')
The above code prints a space at the last. I also don't want that extra space also.
Try this:
s= '12 abc'
a_string = s.split()
capitalized_strings = []
for word in a_string:
capitalized_strings.append(word.capitalize())
print(" ".join(capitalized_strings))
Notice that I am putting the capitalized words into a list and then using join
with this list.
Your problem is that you were passing a string to join
. This treats the string as a list of characters.
So you are basically doing " ".join(["1", "2"])
An explanation of generators:
When you write
word.capitalize() for word in a_string
it returns something called a generator
. A generator is "iterable" like a list.
For example, if you did this (where a_string
is a list of strings):
a_string = ["12", "abc"]
list_of_words = [word.capitalize() for word in a_string]
print(list_of_words)
then you would get this:
["12", "Abc"]
That is called a "list comprehension".
So when you write:
" ".join(word.capitalize() for word in a_string)
it gives the same result as if you did this:
" ".join(["12", "Abc"])
So join
will join the 2 elements in that list, with a " " space between them.
This is different to calling:
" ".join("Abc")
If you pass a string to join
, it is the same as if you did this:
" ".join(["A", "b", "c"])
because the string gets interpreted as a "list of characters".
Use this code to see everything printed as it is calculated step-by-step:
s = "12 abc"
print(s)
s_list = s.split()
print(s_list)
s_capitalized_list = [x.capitalize() for x in s_list]
print(s_capitalized_list)
result = " ".join(s_capitalized_list)
print(result)
Notice that I used x
in my generator in the list comprehension. This is to show you that the name you choose does not matter.