-2
def main():
    print('Please enter a sentence without spaces and each word has ' + \
          'a capital letter.')
    sentence = input('Enter your sentence: ')

    for ch in sentence:
        if ch.isupper():
            capital = ch
            sentence = sentence.replace(capital, ' ' + capital)


main()

Ex: sentence = 'ExampleSentenceGoesHere'

I need this to print as: Example sentence goes here

as of right now, it prints as: Example Sentence Goes Here (with space at the beginning)

Bach
  • 6,145
  • 7
  • 36
  • 61
  • 3
    "Formatting your code" generally means changing the format of the _source code_ for a program. You're asking about how to format a string. – alecbz Apr 16 '14 at 22:55
  • 4
    What exactly is your question? What does not work about the code you just posted? – Energya Apr 16 '14 at 22:56
  • What exactly is being asked here? You need to be much clearer. *Example sentence... prints as: *: include in the question us that actual print command and its output, and use ^^ underneath to highlight where the unwanted space is. – smci Apr 16 '14 at 23:03

3 Answers3

1

You can iterate over the string character by character and replace every upper case letter with a space and appropriate lower case letter:

>>> s = 'ExampleSentenceGoesHere'
>>> "".join(' ' + i.lower() if i.isupper() else i for i in s).strip().capitalize()
'Example sentence goes here'

Note that check if the string is in upper case is done by isupper(). Calling strip() and capitalize() just helps to deal with the first letter.

Also see relevant threads:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1

You need to convert the each uppercase letter to a lowercase one using capital.lower(). You should also ignore the first letter of the sentence so it stays capitalised and doesn't have a space first. You can do this using a flag as such:

is_first_letter = True
for ch in sentence:
    if is_first_letter:
        is_first_letter = False
        continue
    if ch.isupper():
        capital = ch
        sentence = sentence.replace(capital, ' ' + capital.lower())
joc
  • 1,058
  • 7
  • 8
0

I'd probably use re and re.split("[A-Z]", text) but I'm assuming you can't do that because this looks like homework. How about:

def main():
    text = input(">>")
    newtext = ""
    for character in text:
        if character.isupper():
            ch = " " + character.lower()
        else:
            ch = character
        newtext += ch
    text = text[0]+newtext[2:]

You could also do:

transdict = {letter:" "+letter.lower() for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
transtable = str.maketrans(transdict)
text.translate(transtable).strip().capitalize()

But again I think that's outside the scope of the assignment

Adam Smith
  • 52,157
  • 12
  • 73
  • 112