LeoGER
LeoGER

Reputation: 357

Why am I getting an unexpected string when using .format to slice list?

I am trying to create a game of rock, paper, scissors. However, when I try to .format a string inside of an input function using a slice I am getting the following:Choose Rock, Sciss or Scissors:

I am using the following script:

options = ['rock', 'paper', 'scissors']

def rock_paper_scissors():
    x = ''
    for option in options:
        if x == '':
            x += option.title()
    else:
        x += ', ' + option.title()

    player = input('Choose {} or {}:'.format(x[0:11], x[-8:]))

Upvotes: 2

Views: 29

Answers (1)

Gloweye
Gloweye

Reputation: 1428

It's not the slicing that's going wrong, it's the string construction. You should indent the else: block a bit more. For reference, try print()-ing x before your input command.

What happened

Python for loops can have an else: clause. These are executed unless a loop is terminated by break or return. Therefore, your loop only did something on the first iteration while x was still an empty string, and then the else clause would modify your string with the option still bound from the last iteration of your loop.

Edit

Perhaps I'm a bit to used to Code Review, but I'd suggest doing the construction differently, more like this:

player_move = input(f"Choose {', '.join(options[:-1])} or {options[-1]}")

Do note, though, that this will only work for a 3+ length for options. To get a fitting string for less options requires a more... elegant construction.

Upvotes: 1

Related Questions