简体   繁体   中英

comprehension list vs for loop

I have written a simple program that will take the first letter of a string and capitalize it.

def initials(text):
    words = text.split()
    a=[word[0].upper() for word in words]
    b = '. '.join(a) + '.'
    return b
text = "have a good day sir"

print(initials(text))

This will give me the result i want by using a list comprehension. however i cannot make it work by using a typical FOR LOOP as below and it will give me only the last iteration:

def initials(text):
    words = text.split()
    for word in words:
        a=word[0].upper()
        b = '.'.join(a) + '.'
    return b
text = "have a good day sir"

print(initials(text))

any idea why the second example doesn't work as the first one?

b is being reset every time around the loop in the second case. So you only get the last initial followed by . . The equivalent to your comprehension in a for loop, would be:

def initials(text):
    words = text.split()
    a = []
    for word in words:
        a.append(word[0].upper())
    b = '.'.join(a) + '.'
    return b

You're overwriting b on each loop iteration. Try:

def initials(text):
    words = text.split()
    for word in words:
        a = word[0].upper()
        b += '.'.join(a) + '.'
    return b
text = "have a good day sir"

The problem is that str.join() takes a iterable of strings, but in your second function you are passing a single chararacter. The fact that you are calling it inside the loop does not convert it into a list of characters.

The easiest way for you is to get rid of the str.join() and use a simple string to accumulate the result:

def initials(text):
    words = text.split()
    b = ''
    for word in words:
        a=word[0].upper()
        b += a + '.'
    return b

If you insist in using str.join() you will need a list to accumulate your initials:

def initials(text):
    words = text.split()
    b = []
    for word in words:
        a=word[0].upper()
        b.append(a)
    return '.'.join(b) + '.'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM