如何用下划线替换大写?
我是 Python 新手,我试图将单词中的所有大写字母替换为下划线,例如:
ThisIsAGoodExample
应该变成
this_is_a_good_example
关于如何实现此目的的任何想法/提示/链接/教程?
I'm new to Python and I am trying to replace all uppercase-letters within a word to underscores, for example:
ThisIsAGoodExample
should become
this_is_a_good_example
Any ideas/tips/links/tutorials on how to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这是正则表达式的方式:
这就是说,“在字符串中查找前面没有行首并且后面跟着大写字符的点,然后替换然后我们将整个内容小写()。
Here's a regex way:
This is saying, "Find points in the string that aren't preceeded by a start of line, and are followed by an uppercase character, and substitute an underscore. Then we lower()case the whole thing.
编辑:
实际上,只有当第一个字母是大写时,这才有效。否则这个(取自这里)做了正确的事情:
EDIT:
Actually, this only works, if the first letter is uppercase. Otherwise this (taken from here) does the right thing:
这会生成一个项目列表,其中每个项目都是“_”,如果该字符最初是大写字母,则后跟小写字母;如果不是,则为字符本身。然后它将它们连接在一起形成一个字符串,并删除该过程可能添加的任何前导下划线:
顺便说一句,您还没有指定如何处理字符串中已经存在的下划线。我不知道如何处理这个案子,所以我下注了。
This generates a list of items, where each item is "_" followed by the lowercased letter if the character was originally an uppercase letter, or the character itself if it wasn't. Then it joins them together into a string and removes any leading underscores that might have been added by the process:
BTW, you haven't specified what to do with underscores that are already present in the string. I wasn't sure how to handle that case so I punted.
由于没有其他人提供使用生成器的解决方案,因此这里有一个:
As no-one else has offered a solution using a generator, here's one:
解析你的字符串,每次遇到大写字母时,在它前面插入一个_,然后将找到的字符切换为小写
Parse your string, each time you encounter an upper case letter, insert an _ before it and then switch the found character to lower case
尝试可读版本:
An attempt at a readable version:
我不知道,但我在这里看到的大多数答案都相当复杂;我希望我的解决方案有效 -
使用一个简单的 for 循环打印出有问题的字符串的字符,从而在布局时测试每个字符,我们有;
I don't know but most of the answers I see here are quite complex; I hope my solution works -
using a simple for loop to print out the characters of the string in question, thereby testing each character while it's laid out, we have;