Black Bob
Black Bob

Reputation: 105

can't get right when dealing with uppercasing string

#!/usr/bin/python
# -*- coding: utf-8 -*-
def to_weird_case(string):
    lines = string.split()
    new_word = ''
    new_line = ''
    for word in lines:
        for item in word:
            if word.index(item) %2 ==0:
                item = item.upper()
                new_word += item
            else:
                new_word += item
        new_line = new_word +' '
    return new_line
print to_weird_case('what do you mean')

I want to get WhAt Do YoU MeAn, instead I got WhAtDoYoUMeAn. I already add the line new_line = new_word +' '. where is my problem?

Upvotes: 2

Views: 29

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626927

It is correct that your code did not reset the value of new_word and you overwrote the new_line within the loop, but I'd like to share a next to one-liner solution with a regex:

import re
def to_weird_case(string):
    return re.sub(r'(\S)(\S?)', lambda m: "{0}{1}".format(m.group(1).upper(), m.group(2)), string);
print to_weird_case('what do you mean')

See Python demo

The (\S)(\S?) regex captures a non-whitespace into Group 1 and one or zero non-whitespaces into Group 2, and then, inside the re.sub, the Group 1 value is replaced with the uppercased counterpart.

Look at how (\S)(\S?) matches your what do you mean:

  • wh is matches and w is in Group 1 and h is in Group 2 (enter image description here). The match is passed as m to the lambda expression, and Group 1 is modified, and Group 2 is just passed as is.
  • The next match contains at, and the same thing happens with groups
  • Next, the space is not matched since \S matches any character but a whitespace.
  • do is matched, the same things happens as described above
  • space, yo are matched and handled as described above
  • u + empty space are matched next because the second \S has a ? quantifier that matches one or zero occurrences of the pattern it modifies. Thus, the first char is uppercased and the second empty string is used as is.
  • Then the rest is processed in a similar way.

Upvotes: 1

Psytho
Psytho

Reputation: 3384

First, you overwrite new_line with every iteration. Second, new_word is getting longer because you never "clear" it. Third, you add space to the end of the entire new_line and not after every new word (because of Second).

See comments

def to_weird_case(string):
    lines = string.split()
    new_line = ''
    for word in lines:
        new_word = '' # start new word from an empty string
        for item in word:
            if word.index(item) %2 ==0:
                item = item.upper()
                new_word += item
            else:
                new_word += item
        print new_word
        new_line = new_line + new_word + " " # add new word to the existing new line 
    return new_line

Upvotes: 2

Related Questions