【发布时间】:2015-10-31 15:48:08
【问题描述】:
我在使用 gsub 的 Ruby 中得到了以下函数。
def class_to_endpoint(klass)
klass.name.split('::').last.
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
如何在 Python re 中实现这一点?请帮帮我
在 irb 控制台上试过这个,我可以举几个例子,基本上是在驼峰语法中为每个单词添加一个下划线
-
UserProfile->user_profile -
LastModifiedTime->last_modified_time -
User-Profile->user_profile
回答: 我想这就是我想要的 -> Elegant Python function to convert CamelCase to snake_case?
从上面的链接复制并稍作修改
def class_to_endpoint(name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).replace('-', '_').lower()
【问题讨论】:
-
发布一个示例以及预期的输出。
-
我不知道预期的输出是什么,我正在尝试将此代码转换为 Python。
-
I have no idea what is the expected output,那么如果发布,您在什么基础上接受答案。 -
请找出例子,看起来不错吗?
-
伙计们,谁能告诉我downwote的原因?因为它,我不再在 SO 上发布问题!