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

无人久伴 提交于 2021-02-04 21:41:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!