0

how can i change string using for-loop without regex.

example : (python 2.7.1)

import re
trans = lambda src: re.sub("([A-Z])", lambda m:"_"+m.group().lower(), src, flags=0)
print(trans("helloWorld"))

i expect to result as :

hello_world

i want to change from regex version into for-loop version.

conditions

  • the result will be the same
  • just one line!
  • using for loop
user3736174
  • 333
  • 2
  • 3
  • 16
  • Whenever I see named `lambda`s with embedded `lambda`s, I think "coding competition/challenge." Is that what this is for? If not, I highly recommend against this practice. – TigerhawkT3 Sep 07 '16 at 06:40
  • You should avoid trying to do everything in one line… it just leads to unreadable results (and is often downright impossible in Python). – poke Sep 07 '16 at 06:50
  • 1
    If you're trying to convert camelCase to underscores, you should probably survey all the answers from this question: http://stackoverflow.com/q/1175208 –  Sep 07 '16 at 07:03
  • You cannot use a real for loop within a single line as a for loop has to be on its own line in Python. You could use a list comprehension in a single line which also uses the `for` keyword but is technically not a for loop. As for actual solutions to your problem, check the linked question; there are a few one-liners in there. – poke Sep 07 '16 at 07:09

2 Answers2

1
def change(string):
    for letter in string:
        if letter.isupper():
            yield '_{}'.format(letter.lower())
        else:
            yield letter

print ''.join(change("helloWorld"))

If you want to have it in one line:

print ''.join(letter.isupper() and '_{}'.format(letter.lower()) or letter for letter in 'helloWorld')
turkus
  • 4,637
  • 2
  • 24
  • 28
0

You may achieve it using list comprehension (i.e one liner for loop) as:

>>> my_string = "helloWorld"
>>> ''.join(['_{}'.format(s.lower()) if s.isupper() else s for s in my_string])
'hello_world'

Explanation:

List is nothing but a list of chars. Iterate over each char and check whether it is upper case character using isupper() fuct. If it is, replace it to _<lower-case> using lower() func.

The result of above list comprehension is: ['h', 'e', 'l', 'l', 'o', '_w', 'o', 'r', 'l', 'd']. Join the list to find your string i.e. hello_world

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126