Search code examples
pythonpython-2.7textreplacelowercase

How to change upper case letters to lower case letters and spaces to underscores


I would like to change the upper case string characters in a variable to lower case and replace the spaces with "_". I know I can use an 'if' statement for all instances but this would take too long. It is to save the input of a user to a filename i.e.

user_selection = 'Barracuda Limited'  # what I have
save_name == 'barracuda_limited'       # what I want

Note: I have read through the page on how to post and am trying my best, but I have just started to learn coding and am having trouble trying to frame my questions.


Solution

  • This is straightforward, using the str.lower() and str.replace() methods:

    >>> user_selection = 'Barracuda Limited'
    >>> save_name = user_selection.lower().replace(' ', '_')
    >>> save_name
    'barracuda_limited'