pythonpython-3.xlistformatted-text

Python - Print contents of list and include square brackets but not apostrophes


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.


Solution

  • 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]: