python 在python中将camel-case转换为snake-case。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 在python中将camel-case转换为snake-case。相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env python

"""
Convert camel-case to snake-case in python.

e.g.: CamelCase -> snake_case

Relevant StackOverflow question: http://stackoverflow.com/a/1176023/293064
"""

__author__ = 'Jay Taylor [@jtaylor]'


import re


_underscorer1 = re.compile(r'(.)([A-Z][a-z]+)')
_underscorer2 = re.compile('([a-z0-9])([A-Z])')

def camelToSnake(s):
    """ 
    Is it ironic that this function is written in camel case, yet it
    converts to snake case? hmm..
    """
    subbed = _underscorer1.sub(r'\1_\2', s)
    return _underscorer2.sub(r'\1_\2', subbed).lower()

if __name__ == '__main__':
    assert camelToSnake('snakesOnAPlane') == 'snakes_on_a_plane'
    assert camelToSnake('SnakesOnAPlane') == 'snakes_on_a_plane'
    assert camelToSnake('snakes_on_a_plane') == 'snakes_on_a_plane'
    assert camelToSnake('IPhoneHysteria') == 'i_phone_hysteria'
    assert camelToSnake('iPhoneHysteria') == 'i_phone_hysteria'
    print 'All tests passed.'

以上是关于python 在python中将camel-case转换为snake-case。的主要内容,如果未能解决你的问题,请参考以下文章

python 在Python中将ASCII转换为String

python 在Python中将字符串转换为数组

python 如何在python中将参数提供给命令行

python 在Pandas(Python)中将整数转换为浮点格式

Python:在python编程中将扫描的pdf转换为excel

在Debian9中将python版本添加到vscode