我是新来的Python,我试图取代一个字为下划线内的所有大写,字母,例如:如何用下划线替换大写字母?
ThisIsAGoodExample
应该成为
this_is_a_good_example
任何想法/提示/链接/如何实现这个教程?
我是新来的Python,我试图取代一个字为下划线内的所有大写,字母,例如:如何用下划线替换大写字母?
ThisIsAGoodExample
应该成为
this_is_a_good_example
任何想法/提示/链接/如何实现这个教程?
解析你的字符串,每次遇到一个大写字母时,在它前面插入一个_,然后切换发现字符为小写
import re
"_".join(l.lower() for l in re.findall('[A-Z][^A-Z]*', 'ThisIsAGoodExample'))
编辑: 其实,这只是作品,如果第一字母大写。否则,这(从here拍摄)做正确的事:
def convert(name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
别紧张上的新手。 :) –
example = 'ThisIsAGoodExample'
# Don't put an underscore before first character.
new_example = example[0]
for character in example[1:]:
# Append an underscore if the character is uppercase.
if character.isupper():
new_example += '_'
new_example += character.lower()
用'if character.isupper()'替换第6行,它也应该处理unicode。 –
@Kirk,谢谢。固定。 –
这里有一个正则表达式的方法:
import re
example = "ThisIsAGoodExample"
print re.sub('(?<!^)(?=[A-Z])', '_', example).lower()
这是在说,“找点串在不通过线的开始preceeded和是跟着是一个大写字符,并代之以一个下划线。然后我们降低()的情况下,整个事情。
错过了大量的大写字母。例如,它不会处理我的名字拼写,例如“Éric”。 IIRC,'\ p {Lu}'是合适的模式,而不是'[A-Z]'。 – ikegami
由于没有其他人提供了使用发电机的解决方案,这是一个:
>>> sample = "ThisIsAGoodExample"
>>> def upperSplit(data):
... buff = ''
... for item in data:
... if item.isupper():
... if buff:
... yield buff
... buff = ''
... buff += item
... yield buff
...
>>> list(upperSplit(sample))
['This', 'Is', 'A', 'Good', 'Example']
>>> "_".join(upperSplit(sample)).lower()
'this_is_a_good_example'
这生成项目,其中每个项目是列表“_”后面的小写字母,如果角色原本是大写字母或字符本身(如果不是)。然后将它们串联在一起成一个字符串,并删除可能已被处理过程中添加任何前导下划线:
print ''.join('_' + char.lower() if char.isupper() else char
for char in inputstring).lstrip('_')
顺便说一句,你还没有指定如何处理已经存在的字符串中的下划线做。我不知道如何处理这种情况,所以我踢了。
http://stackoverflow.com/questions/1175208/does-the-python-standard-library-have-function-to-convert-camelcase-to-camel-case –
你给的例子不匹配标题也不匹配这个问题的描述。你是否试图用下划线替换所有大写字符,或者你是否试图将CamelCase转换为lowercase_underscore_separated?你会发现,除非你能够用文字解释你想要做什么,否则用Python(或任何其他语言)解决它将会非常具有挑战性。 – Johnsyweb