zmd809
zmd809

Reputation: 3

Changing capitalization with for loops and list comprehension

I have a assignment where I need to

sometimes it might be useful to convert text from lowerCamelCase to snake_case. The main trick is to find the correct place where to insert an underscore. Let's make a rule that it's right before a capital letter of the next word. If the first letter is capitalized, convert it to lowercase and don't forget to insert an underscore before it.

I wrote my code and for some reason it doesn't return anything, it's completely empty, my ide says I have no errors

word = input()
new_word = ''
for char in word:
    if char.isupper():
        new_word.join('_' + char.lower())
    else:
        new_word.join(char)
print(new_word)

The assignment runs multiple tests with different words, and here they are

Sample Input 1:

python

Sample Output 1:

python

Sample Input 2:

parselTongue

Sample Output 2:

parsel_tongue

I legitimately don't see any reason why it's not printing, any ideas why

Upvotes: 0

Views: 96

Answers (3)

fsimonjetz
fsimonjetz

Reputation: 5802

As your title says "list comprehension", here is an approach that utilizes a comprehension:

snake_word = ''.join(f'_{c.lower()}' if c.isupper() else c for c in word)

Upvotes: 0

Ram
Ram

Reputation: 4779

You are almost there. You have to concatenate the characters to new_word and not join.

This is Concatenation. char gets appended to new_word:

new_word += char

join() will just concatenate and return the strings passed to it. But it is not saved to new_word.

Use concatenation instead of join in your code.

word = input('Input: ')
new_word = ''
for char in word:
    if char.isupper():
        new_word += '_' + char.lower()
    else:
        new_word += char
print(f'Output: {new_word}')


Input: python
Output: python

Input: parselTongue
Output: parsel_tongue

Upvotes: 1

MundaneHassan
MundaneHassan

Reputation: 146

It's because the 1st test case is all lower case. new_word will be empty because loop's inner condition won't execute at all. Here's the correct and cleaner code I wrote

word = input()
counter = 0
new_word = ""

for char in word:
    if not(char.islower()) and counter > 0:
        new_word = new_word + '_' + char.lower()
    else:
        new_word = new_word + char.lower()
    counter += 1
    
print(new_word)

Upvotes: 1

Related Questions