Exercise 8/11 - Can this be simplified?


#1

Could we simplify the code and write this instead? (Not for the purpose of the exercise…but if we were writing this code ourselves)

pyg = ‘ay’

original = raw_input(‘Enter a word:’)

if len(original) > 0 and original.isalpha():
word = original.lower()
new_word = word[1: ] + word[0] + pyg
print new_word
else:
print ‘empty’


#2

According to the instructions, this should be,

new_word = word + first + pyg
new_word = new_word[1:len(new_word)]

but yes, your simplification will work fine. Just don’t expect it to be accepted by the SCT.


#3

Thank you :slight_smile:


#4

We are also allowed to build strings with string formatting.

new_word = "%s%s%s" % (word[1:], word[0], pyg)

or in newer syntax,

new_word = "{}{}{}".format(word[1:], word[0], pyg)

#5

Oh, that’s great. That takes what I was thinking a step further, and I appreciate that. Thanks for the insight!


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.