mchd
mchd

Reputation: 3163

Python iterations mischaracterizes string value

For this problem, I am given strings ThatAreLikeThis where there are no spaces between words and the 1st letter of each word is capitalized. My task is to lowercase each capital letter and add spaces between words. The following is my code. What I'm doing there is using a while loop nested inside a for-loop. I've turned the string into a list and check if the capital letter is the 1st letter or not. If so, all I do is make the letter lowercase and if it isn't the first letter, I do the same thing but insert a space before it.

def amendTheSentence(s):
    s_list = list(s)

    for i in range(len(s_list)):

        while(s_list[i].isupper()):
            if (i == 0):
                s_list[i].lower()
            else:
                s_list.insert(i-1, " ")
                s_list[i].lower()

    return ''.join(s_list)

However, for the test case, this is the behavior:

Input:  s:        "CodesignalIsAwesome"
Output:           undefined
Expected Output:  "codesignal is awesome"
Console Output:   Empty

Upvotes: 4

Views: 82

Answers (3)

Gerry P
Gerry P

Reputation: 8092

def amendTheSentence(s):
    new_sentence=''
    for char in s:
        if char.isupper():
            new_sentence=new_sentence + ' ' + char.lower() 
        else:
            new_sentence=new_sentence + char
    return new_sentence  

new_sentence=amendTheSentence("CodesignalIsAwesome") 
print (new_sentence)

result is  codesignal is awesome

Upvotes: 1

Shubham Sharma
Shubham Sharma

Reputation: 71689

Try this:

def amendTheSentence(s):
    start = 0
    string = ""
    for i in range(1, len(s)):
        if s[i].isupper():
            string += (s[start:i] + " ")
            start = i

    string += s[start:]
    return string.lower()


print(amendTheSentence("CodesignalIsAwesome"))
print(amendTheSentence("ThatAreLikeThis"))

Output:

codesignal is awesome
that are like this

Upvotes: 1

Austin
Austin

Reputation: 26039

You can use re.sub for this:

re.sub(r'(?<!\b)([A-Z])', ' \\1', s)

Code:

import re

def amendTheSentence(s):
    return re.sub(r'(?<!\b)([A-Z])', ' \\1', s).lower()

On run:

>>> amendTheSentence('GoForPhone')
go for phone

Upvotes: 4

Related Questions