sk11
sk11

Reputation: 1824

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 e.g. 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.

Upvotes: 3

Views: 17746

Answers (3)

redd16
redd16

Reputation: 21

string = input()

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

Upvotes: 2

Mark
Mark

Reputation: 92460

Why not a simple regex:

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

# result '_one_world_is_not_enough_to_live'

Upvotes: 13

Sesha
Sesha

Reputation: 202

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

Upvotes: 4

Related Questions