例子:
>>> convert('CamelCase')
'camel_case'
例子:
>>> convert('CamelCase')
'camel_case'
当前回答
哇,我刚从django片段中偷了这个。ref http://djangosnippets.org/snippets/585/
很优雅
camelcase_to_underscore = lambda str: re.sub(r'(?<=[a-z])[A-Z]|[A-Z](?=[^A-Z])', r'_\g<0>', str).lower().strip('_')
例子:
camelcase_to_underscore('ThisUser')
返回:
'this_user'
REGEX演示
其他回答
这个简单的方法应该可以做到:
import re
def convert(name):
return re.sub(r'([A-Z]*)([A-Z][a-z]+)', lambda x: (x.group(1) + '_' if x.group(1) else '') + x.group(2) + '_', name).rstrip('_').lower()
我们寻找前面有任意数量的(或零)大写字母,后面有任意数量的小写字符的大写字母。 在组中发现的最后一个大写字母之前放置下划线,如果前面有其他大写字母,则可以在该大写字母之前放置下划线。 如果后面有下划线,删除它们。 最后,整个结果字符串被改为小写。
(从这里开始,见在线工作示例)
这个网站上提出了非常好的RegEx:
(?<!^)(?=[A-Z])
如果python有一个字符串分割方法,它应该工作…
在Java中:
String s = "loremIpsum";
words = s.split("(?<!^)(?=[A-Z])");
def convert(name):
return reduce(
lambda x, y: x + ('_' if y.isupper() else '') + y,
name
).lower()
如果我们需要覆盖一个已经没有驼峰输入的情况:
def convert(name):
return reduce(
lambda x, y: x + ('_' if y.isupper() and not x.endswith('_') else '') + y,
name
).lower()
使用:str.capitalize()将字符串(包含在变量str中)的首字母转换为大写字母,并返回整个字符串。
例子: 命令:“你好”.capitalize () 输出:你好
就我个人而言,我不确定在python中使用正则表达式的任何东西都可以被描述为优雅。这里的大多数答案只是做“代码高尔夫”类型的RE技巧。优雅的编码应该是容易理解的。
def to_snake_case(not_snake_case):
final = ''
for i in xrange(len(not_snake_case)):
item = not_snake_case[i]
if i < len(not_snake_case) - 1:
next_char_will_be_underscored = (
not_snake_case[i+1] == "_" or
not_snake_case[i+1] == " " or
not_snake_case[i+1].isupper()
)
if (item == " " or item == "_") and next_char_will_be_underscored:
continue
elif (item == " " or item == "_"):
final += "_"
elif item.isupper():
final += "_"+item.lower()
else:
final += item
if final[0] == "_":
final = final[1:]
return final
>>> to_snake_case("RegularExpressionsAreFunky")
'regular_expressions_are_funky'
>>> to_snake_case("RegularExpressionsAre Funky")
'regular_expressions_are_funky'
>>> to_snake_case("RegularExpressionsAre_Funky")
'regular_expressions_are_funky'