Search code examples
pythonstring

Is there a way to shorten this code to two lines maybe three?


I am still figuring out how to manipulate strings in python. Currently I need to use 4 lines to go from

('Al Jahar',)

to

'Al Jahar'

This is the code I'm using. Works great, but would love to make it more elegant and pythonic.

    selected_monster = f"{selected_monster}"
    selected_monster = selected_monster[:-2] + selected_monster[-1]
    selected_monster = selected_monster[:-1]
    selected_monster = selected_monster[1:]
    print(selected_monster)

I can't just strip/ replace the characters "()," with "" because some monster names have those characters in their titles, eg: 'Beholder (blah blah)' or 'Dragon, Green'. The names ALL come from a db and have this markup around their 'Monster Name' name tag. So if I try the replacement method it messes up the titles and I can't use them as string variables in my code.


Solution

  • ('Al Jahar',) is a tuple. You can determine this by doing

    >>> selected_monster = ('Al Jahar',)
    >>> type(selected_monster)
    

    To access an element of a tuple, you can just index it:

    >>> selected_monster[0]
    

    OR

    >>> ('Al Jahar',)[0]
    

    You can also use tuple unpacking. The version below is if you're sure it contains only one element:

    >>> selected_monster, = selected_monster
    

    If you're not sure, stash the remainder elsewhere:

    >>> selected_monster, *_ = selected_monster
    

    You may also want to reconsider how you generate selected_monster in the first place, if you need it to be a string.