【问题标题】:Replace uppercase characters with lowercase+extra characters用小写+多余字符替换大写字符
【发布时间】:2014-08-06 07:33:50
【问题描述】:

我正在尝试查找字符串中的所有大写字母并将其替换为小写加上underscore 字符。 AFAIK 没有标准的字符串函数来实现这个(?)

例如如果输入字符串是'OneWorldIsNotEnoughToLive',那么输出字符串应该是'_one_world_is_not_enough_to_live'

我可以使用以下代码来做到这一点:

# This finds all the uppercase occurrences and split into a list 
import re
split_caps = re.findall('[A-Z][^A-Z]*', name)
fmt_name = ''
for w in split_caps:
    fmt_name += '_' + w # combine the entries with underscore
fmt_name = fmt_name.lower() # Now change to lowercase
print (fmt_name)

我认为这太过分了。首先re,然后是列表迭代,最后转换为小写。也许有更简单的方法来实现这一点,更多的pythonic和1-2行。

请提出更好的解决方案。谢谢。

【问题讨论】:

  • 这不是代码编写服务。你为什么不看看the str methods“没有标准的字符串函数” - 你在期待什么,str.uppercase_to_lowercase_with_underscores
  • 我知道 SO 不是代码编写服务。只是想看看有没有更好的解决方案,更多的pythonic和1-2行。
  • 如果你想检查工作代码,试试codereview.stackexchange.com
  • @jonrsharpe 感谢您的链接。我不知道 codereview.stackexchange.com 我会看看。按照标准,我的意思是用某种模式替换字符串。

标签: python regex string str-replace


【解决方案1】:

为什么不是一个简单的正则表达式:

import re
re.sub('([A-Z]{1})', r'_\1','OneWorldIsNotEnoughToLive').lower()

# result '_one_world_is_not_enough_to_live'

【讨论】:

  • 这会将连续的大写字符替换为前面带有单个下划线的小写字符。这应该避免它([A-Z]{1})
【解决方案2】:

试试这个。

string1 = "OneWorldIsNotEnoughToLive"
list1 = list(string1)
new_list = []
for i in list1:
    if i.isupper():
        i = "_"+i.lower()
    new_list.append(i)
print ''.join(new_list)

Output: _one_world_is_not_enough_to_live

【讨论】:

    【解决方案3】:
    string = input()
    
    for letter in string:
        if letter.isupper():
            string = string.replace(letter, "_" + letter.lower())
    print(string)
    

    【讨论】:

      猜你喜欢
      • 2018-12-28
      • 1970-01-01
      • 2016-12-11
      • 2014-03-30
      • 2014-06-20
      • 1970-01-01
      • 2014-01-11
      • 2021-05-31
      • 1970-01-01
      相关资源
      最近更新 更多