1
    my_string = input("Enter words. ")
    i = 0
    result = ()
    for c in my_string:
        if c.isupper() and i > 0:
            result += ( )
            result += c.lower()
        else:
            result += c
        i += 1

    print result

I've been trying to make a word separator for python except I'm having a lot of trouble with it, I've found a similar question on StackOverflow except they don't use an input statement which is what I'm trying to figure out. I have this to go off of, I just need to make it to where there's an input statement involved to ask the user to input whatever they cluster of words they want to be separated. Thanks a lot!

Blake McLaughlin
  • 91
  • 1
  • 2
  • 11
  • `result += ( )` does nothing and `result += c.lower()` should throw a `TypeError`. – cs95 Nov 12 '17 at 23:00
  • I'm sure that if I replace the input statement I've tried to place in the code with "PurpleCows" for example, it will offer a good output. But I'll your comment now. – Blake McLaughlin Nov 12 '17 at 23:02
  • What is the output supposed to be? – cs95 Nov 12 '17 at 23:03
  • It's supposed to take an input and put spaces between the cluster of words that are inputted. For example, you enter "PurpleCowsAreNice" and the output is "Purple Cows Are Nice" – Blake McLaughlin Nov 12 '17 at 23:07

1 Answers1

2

Option 1
Iteration with yield:

In [156]: def split(string):
     ...:     for c in string:
     ...:         if c.isupper():
     ...:             yield ' '
     ...:         yield c
     ...:             

In [157]: ''.join(split("PurpleCowsAreNice"))
Out[157]: ' Purple Cows Are Nice' 

Option 2
re.sub with reference groups:

In [159]: re.sub('([A-Z])', r' \1', "PurpleCowsAreNice")
Out[159]: ' Purple Cows Are Nice'

For simplicity, I've allowed both methods to yield a result with leading spaces, but you could just as easily remove them with str.strip.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Thanks a lot! But is there a way I could make it include an input statement so the program asks the user what cluster of words they want to enter, and then space them out? Sorry if I wasn't clear about that before, I very much appriciate the help! – Blake McLaughlin Nov 12 '17 at 23:19
  • @BlakeMcLaughlin Here's a good [starting point](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response)... You should be able to fit that into your program no problems. – cs95 Nov 12 '17 at 23:20