Home > Mobile >  How do I print the first letter and second letter and third.. of each string in python?
How do I print the first letter and second letter and third.. of each string in python?

Time:08-24

If I enter: 'I love stack overflow', how can I print first&second&third letter from this string.

The output to be like this:

'Ilso', 'otv', 'vae', 'ecr'...

If anyone can help me with this would be great! Thanks :D

CodePudding user response:

Solution

Use str.split, str.join and itertools.zip_longest:

from itertools import zip_longest

s = 'I love stack overflow'

result = [''.join(chars) for chars in zip_longest(*s.split(), fillvalue='')]

print(result)
# ['Ilso', 'otv', 'vae', 'ecr', 'kf', 'l', 'o', 'w']

Explanation

s.split() splits the string into a list of words, seperated by space. zip_longest returns tuples of characters from all words, filling up the missing values (for short words) with the empty string ''. ''.join() concatenates (adds) the characters to a new string. The list comprehension loops over all the letter tuples, first letter, second, etc.

CodePudding user response:

string = 'I love stack overflow'

words = string.split()

longest_word = len(max(words, key=len))

result = [

    ''.join([
        word[index]
        for word in words
        if len(word) > index
    ])
    for index in range(longest_word)
]

print(result)

CodePudding user response:

This can be the solution

a='I love stack overflow'
l=a.split()
for i in range(len(max(l,key=len))):
    b=''
    for j in l:
        try:
            b=b j[i]
        except Exception:
            pass
    print(b)
  • Related