user12555224
user12555224

Reputation:

Code to print the first and last letters of each word

I am making a code that fetches song names and artists from an external file and prints the first letter of each word in the name of the song and then prints the artist's name. I have completed this element of the code, and I am now attempting to create a part of the code that, when the user gets the guess wrong of the song name on their first try, my program prints the last letter of each word in the title as well. The code I came up with, which will be printed below worked well except for when one of the words was one letter long, because it would print that letter twice as it was both the first and the last letter.

Here is the code I had that worked for everything except one letter words:

print(' '.join(x[0] + '_' * (len(x) - 2) + x[-1] for x in song_title.split()))

for example:

input = Axel F
output = A__l FF
desired output = A__l F

If someone could give me some advice on how to achieve this it would be much appreciated

Upvotes: 2

Views: 674

Answers (1)

Jordan Brière
Jordan Brière

Reputation: 1055

You could just validate the length of your word first:

print(' '.join(x[0] + '_' * (len(x) - 2) + (x[-1] if len(x) > 1 else '') for x in song_title.split()))

Upvotes: 3

Related Questions