问题
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.
回答1:
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'
回答2:
In order to get your desired data you can do something like this:
user_selection = 'Barracuda Limited':
save_name = "_".join(k.lower() for k in user_selection.split())
# save_name is: 'barracuda_limited'
来源:https://stackoverflow.com/questions/44184239/how-to-change-upper-case-letters-to-lower-case-letters-and-spaces-to-underscores