Replace uppercase characters with lowercase+extra characters
13,547
Solution 1
Why not a simple regex:
import re
re.sub('([A-Z]{1})', r'_\1','OneWorldIsNotEnoughToLive').lower()
# result '_one_world_is_not_enough_to_live'
Solution 2
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
Solution 3
string = input()
for letter in string:
if letter.isupper():
string = string.replace(letter, "_" + letter.lower())
print(string)
Comments
-
sk11 almost 2 years
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.
-
jonrsharpe almost 10 yearsThis isn't a code-writing service. Why don't you have a look at the
str
methods. "there is no standard string function" - what were you expecting,str.uppercase_to_lowercase_with_underscores
? -
sk11 almost 10 yearsI am aware that SO is not a code writing service. Just wanted to see if there are better solutions, more pythonic and 1-2 lines.
-
jonrsharpe almost 10 yearsIf you want working code reviewed, try codereview.stackexchange.com
-
sk11 almost 10 years@jonrsharpe Thanks for the link. I didn't know about codereview.stackexchange.com I will give it a look. By standard I meant replacing a string with some pattern.
-
-
se7entyse7en almost 10 yearsThis will replace consecutive uppercase characters with lowercase characters preceded by a single underscore. This should avoid it
([A-Z]{1})