0

As the title outlines, I have defined a list variable of strings and I need to print the contents of the list as part of an input line, which also includes other text, and I need the contents of the list printed to screen WITH the square brackets but WITHOUT the apostrophes.

Here is my code:

interactive_options = ['list', 'heroes', 'villains', 'search', 'reset', 'add', 'remove', 'high', 'battle', 'health', 'quit']
user_choice = input(f'''
Please enter a choice \n{interactive_options}
''')

The current output is:

Please enter a choice

['list', 'heroes', 'villains', 'search', 'reset', 'add', 'remove', 'high', 'battle', 'health', 'quit']

... whereas I need:

Please enter a choice

[list, heroes, villains, search, reset, add, remove, high, battle, health, quit]:

Note - I also need a colon printed at the end of the list contents but can't get this to work either.

K-J
  • 99
  • 9
  • 1
    If you print the list itself, you have absolutely no control over the formatting - you get whatever the list's `str()` gives you. You need to turn it into a string yourself - `", ".join(interactive_options)` would be a start. – jasonharper Feb 15 '22 at 22:36
  • That's helpful actually. I probably don't need to specifically print the list in this instance. I can just write the options in reg. text in this part of the code. Seems obvious now that I think about it :/ Thank you! – K-J Feb 15 '22 at 22:41
  • 2
    Does this answer your question? [How to concatenate items in a list to a single string?](https://stackoverflow.com/questions/12453580/how-to-concatenate-items-in-a-list-to-a-single-string) – Pranav Hosangadi Feb 15 '22 at 23:35

2 Answers2

1

If you are using print(interactive_options) - you get the result of str(interactive_options):

>>> print(interactive_options)
['list', 'heroes', 'villains', 'search', 'reset', 'add', 'remove', 'high', 'battle', 'health', 'quit']
>>> str(interactive_options)
['list', 'heroes', 'villains', 'search', 'reset', 'add', 'remove', 'high', 'battle', 'health', 'quit']

However, you can use join (which returns a string by joining all the elements of an iterable (list, string, tuple), separated by a string separator) to format the output as you wish, like so:

>>> ", ".join(interactive_options)
list, heroes, villains, search, reset, add, remove, high, battle, health, quit

You can add then the brackets and colon to the output:

>>> interactive_options_print = ", ".join(interactive_options)
>>> interactive_options_print = "[" + interactive_options_print + "]:"
>>> interactive_options_print
[list, heroes, villains, search, reset, add, remove, high, battle, health, quit]:
-1

You may try this -

interactive_options = ['list', 'heroes', 'villains', 'search', 'reset', 'add', 'remove', 'high', 'battle', 'health', 'quit']
user_choice = input(f'''
Please enter a choice \n{str(interactive_options).replace("'","")}:
''')
Kaish kugashia
  • 234
  • 2
  • 8