Search code examples
pythonstringstring-function

If input is: Jane Silly Doe Output is: Doe, J.S. If input is: Julia Clark Output is: Clark, J. Issue: I can make it run for either or but not both


If input is: Jane Silly Doe Output is: Doe, J.S.

If input is: Julia Clark Output is: Clark, J. Issue:

I can make it run for either or but not both

This only works for input Jane Silly Doe but not for input Julia Clark. I can make it run for either or but not both at the same time.

string = input()
words = string.split()
title = ''
for word in words:
    title += word

another = (words[-1]+',')
second = (words[0])
third = (words[1])
fourth = second + third

upper = ''
for char in fourth:
    if char.isupper():
        upper += char

join_string = '.'.join(upper)
print(another, join_string + '.')

Solution

  • You can use fixed index like words[1] use slicing words[:-1] to get all values except the last one

    def shorten(string):
        words = string.split()
        result = words[-1] + ', '
        for char in ''.join(words[:-1]):
            if char.isupper():
                result += char + "."
        print(result)
    
    shorten("Julia Clark")  # Clark, J.
    shorten("Jane Silly Doe")  # Doe, J.S.
    shorten("Jane Silly Jack James Doe")  # Doe, J.S.J.J.