简体   繁体   中英

Replace uppercase characters with lowercase+extra characters

I am trying to find all the uppercase letters in a string and replace it with the lowercase plus underscore character. AFAIK there is no standard string function to achieve this (?)

For eg if the input string is 'OneWorldIsNotEnoughToLive' then the output string should be '_one_world_is_not_enough_to_live'

I am able to do it with the following piece of code:

# 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)

I think this is too much. First re , followed by list iteration and finally converting to lowercase. Maybe there is a simpler way to achieve this, more pythonic and 1-2 lines.

Please suggest better solutions. Thanks.

Why not a simple regex:

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

# result '_one_world_is_not_enough_to_live'

Try this.

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
string = input()

for letter in string:
    if letter.isupper():
        string = string.replace(letter, "_" + letter.lower())
print(string)

Does anyone know how to modify the answer so that it only does the underscore for the First of several uppercase in a row.

I want if the input was : OneWorldIsNotEnoughToLIVE

the answer would still be : _one_world_is_not_enough_to_live

NOT : _one_world_is_not_enough_to_l_i_v_e

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM