下面是我的代码,我想知道是否有一种方法来保持大小写的方式?
比如"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
。
发布于 2021-08-09 18:42:16
您可以手动仅将第一个字符大写:
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 = ''
。
发布于 2021-08-09 19:00:36
只有大写的字母紧跟在下划线之后,不要触摸其他任何东西,所以矛盾的是,.capitalize()
不是你想要的机器人。下面是基于Making letters uppercase using re.sub的正则表达式方法
>>> re.sub('_.', lambda mat: mat.group(0).upper(), 'num_to_SMS')
'num_To_SMS'
(在re.sub
中,可调用的repl
参数可以是一个函数(‘’),在这种情况下,它会传递给匹配对象mat
。我们可以用它来解决Python缺少扩展正则表达式运算符的问题,比如大写\U
,而PERL等都有。也有针对这些的第三方Python包。)
发布于 2021-08-09 19:18:17
尝试:
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
https://stackoverflow.com/questions/68720394
复制相似问题