【问题标题】:Keep capitals in snake_case to camel case将snake_case中的大写字母保留为camel case
【发布时间】:2021-08-10 02:22:52
【问题描述】:

下面是我的代码,我想知道是否有办法让大写保持原样?

比如“num_to_SMS”还是会变成“numToSMS”?

def to_camel(ident):
  return ''.join(x.capitalize() or '_' for x in ident.split('_'))

print(to_camel('foo'))
print(to_camel('raw_input'))
print(to_camel('num2words'))
print(to_camel('num_to_SMS'))

到目前为止,最后一个示例根据需要输出 numToSms 而不是 numToSMS

【问题讨论】:

  • 题外话,or '_' 应该做什么?
  • 我怀疑使用后向断言来处理前面带有“_”的正则表达式会更简单,尽管\U 大写运算符需要扩展正则表达式语法。

标签: python camelcasing


【解决方案1】:

您可以手动只将第一个字符大写:

def to_camel(ident):
    return ''.join(x[:1].upper() + x[1:] for x in ident.split('_'))

for s in 'foo', 'raw_input', 'num2words', 'num_to_SMS':
    print(to_camel(s))

输出:

Foo
RawInput
Num2words
NumToSMS

我使用切片以防万一x = ''

【讨论】:

  • 很抱歉,这不是 OP 所要求的。见帖子最后一行:So far the last example outputs numToSms not numToSMS as desired.
【解决方案2】:

只大写紧跟下划线的字母,不要碰其他任何东西,所以.capitalize() 矛盾的是不是你想要的机器人。这是基于Making letters uppercase using re.sub的正则表达式方法:

>>> re.sub('_.', lambda mat: mat.group(0).upper(), 'num_to_SMS')

'num_To_SMS'

(在re.sub中,repl 参数可以是一个函数('callable'),在这种情况下,它传递了 Match 对象 mat。我们可以使用它来解决 Python缺少扩展的正则表达式运算符,例如大写 \U,PERL 等具有。还有第三方 Python 包。)

【讨论】:

  • 很抱歉,这不是 OP 所要求的。见帖子最后一行:So far the last example outputs numToSms not numToSMS as desired.
【解决方案3】:

尝试:

def to_camel(ident):
    lst = ident.split('_')
    return ''.join(x[:1].upper() + x[1:] if not ((x.isupper() and x.isalpha()) 
    or lst.index(x)==0) else (x if lst.index(x) != 0 else x.lower()) for x in lst)

此代码强制将单词的第一个字母大写,如果它们不是起始单词并且不是全部大写,并且如果单词不是起始单词,则保留所有大写单词。

输出:

foo
rawInput
num2words
numToSMS

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 2015-07-28
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多