如何用下划线替换大写?

发布于 2024-12-03 08:09:51 字数 184 浏览 1 评论 0原文

我是 Python 新手,我试图将单词中的所有大写字母替换为下划线,例如:

ThisIsAGoodExample

应该变成

this_is_a_good_example

关于如何实现此目的的任何想法/提示/链接/教程?

I'm new to Python and I am trying to replace all uppercase-letters within a word to underscores, for example:

ThisIsAGoodExample

should become

this_is_a_good_example

Any ideas/tips/links/tutorials on how to achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

不美如何 2024-12-10 08:09:51

这是正则表达式的方式:

import re
example = "ThisIsAGoodExample"
print re.sub( '(?<!^)(?=[A-Z])', '_', example ).lower()

这就是说,“在字符串中查找前面没有行首并且后面跟着大写字符的点,然后替换然后我们将整个内容小写()。

Here's a regex way:

import re
example = "ThisIsAGoodExample"
print re.sub( '(?<!^)(?=[A-Z])', '_', example ).lower()

This is saying, "Find points in the string that aren't preceeded by a start of line, and are followed by an uppercase character, and substitute an underscore. Then we lower()case the whole thing.

亢潮 2024-12-10 08:09:51
import re
"_".join(l.lower() for l in re.findall('[A-Z][^A-Z]*', 'ThisIsAGoodExample'))

编辑:
实际上,只有当第一个字母是大写时,这才有效。否则这个(取自这里)做了正确的事情:

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()
import re
"_".join(l.lower() for l in re.findall('[A-Z][^A-Z]*', 'ThisIsAGoodExample'))

EDIT:
Actually, this only works, if the first letter is uppercase. Otherwise this (taken from here) does the right thing:

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()
拥醉 2024-12-10 08:09:51

这会生成一个项目列表,其中每个项目都是“_”,如果该字符最初是大写字母,则后跟小写字母;如果不是,则为字符本身。然后它将它们连接在一起形成一个字符串,并删除该过程可能添加的任何前导下划线:

print ''.join('_' + char.lower() if char.isupper() else char
              for char in inputstring).lstrip('_')

顺便说一句,您还没有指定如何处理字符串中已经存在的下划线。我不知道如何处理这个案子,所以我下注了。

This generates a list of items, where each item is "_" followed by the lowercased letter if the character was originally an uppercase letter, or the character itself if it wasn't. Then it joins them together into a string and removes any leading underscores that might have been added by the process:

print ''.join('_' + char.lower() if char.isupper() else char
              for char in inputstring).lstrip('_')

BTW, you haven't specified what to do with underscores that are already present in the string. I wasn't sure how to handle that case so I punted.

尾戒 2024-12-10 08:09:51

由于没有其他人提供使用生成器的解决方案,因此这里有一个:

>>> 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'

As no-one else has offered a solution using a generator, here's one:

>>> 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'
听风念你 2024-12-10 08:09:51
example = 'ThisIsAGoodExample'
# Don't put an underscore before first character.
new_example = example[0].lower()
for character in example[1:]:
    # Append an underscore if the character is uppercase.
    if character.isupper():
        new_example += '_'
    new_example += character.lower()
example = 'ThisIsAGoodExample'
# Don't put an underscore before first character.
new_example = example[0].lower()
for character in example[1:]:
    # Append an underscore if the character is uppercase.
    if character.isupper():
        new_example += '_'
    new_example += character.lower()
风渺 2024-12-10 08:09:51

解析你的字符串,每次遇到大写字母时,在它前面插入一个_,然后将找到的字符切换为小写

Parse your string, each time you encounter an upper case letter, insert an _ before it and then switch the found character to lower case

柒夜笙歌凉 2024-12-10 08:09:51

尝试可读版本:

import re

_uppercase_part = re.compile('[A-Z][^A-Z]*')    

def uppercase_to_underscore(name):
    result = ''
    for match in _uppercase_part.finditer(name):
        if match.span()[0] > 0:
            result += '_'
        result += match.group().lower()
    return result

An attempt at a readable version:

import re

_uppercase_part = re.compile('[A-Z][^A-Z]*')    

def uppercase_to_underscore(name):
    result = ''
    for match in _uppercase_part.finditer(name):
        if match.span()[0] > 0:
            result += '_'
        result += match.group().lower()
    return result
最笨的告白 2024-12-10 08:09:51

我不知道,但我在这里看到的大多数答案都相当复杂;我希望我的解决方案有效 -

使用一个简单的 for 循环打印出有问题的字符串的字符,从而在布局时测试每个字符,我们有;

ourCamelcase = input("somecamelCase: ")
print("thesnake_case: ", end="")

for char in ourcamelCase:
    if c.isupper():
        print("_" + char.lower(), end="")
    else:
        print(char, end="")

print("")

I don't know but most of the answers I see here are quite complex; I hope my solution works -

using a simple for loop to print out the characters of the string in question, thereby testing each character while it's laid out, we have;

ourCamelcase = input("somecamelCase: ")
print("thesnake_case: ", end="")

for char in ourcamelCase:
    if c.isupper():
        print("_" + char.lower(), end="")
    else:
        print(char, end="")

print("")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文