my name is bishop
I am a python programmer
I am a writer
I practice zen meditation
I am a musician
I am in peak physical health
I am a photographer
I speak fluent russian


and I do not exist.........yet

Fun with strings and the “for” loop

August 31st, 2007 by Robert

I was asked to take this code:


prefixes = "JKLMNOPQ"
suffix = "ack"

for letter in prefixes:
print letter + suffix

which produced the following output:


Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack

and rewrite it so that Oack and Qack would actually be Ouack and Quack. Here is what I did:


prefix = 'JKLMNOPQ'
suffix = 'ack'

for letter in prefix:
if letter == 'Q' or letter == 'O':
print letter + 'u' + suffix
else:
print letter + suffix

Here was the result:

Jack
Kack
Lack
Mack
Nack
Ouack
Pack
Quack

Yay! I’m going to revisit it though and see if there is a better way of coding it. For now, I’m just happy it worked.

Posted in python |

2 Responses

  1. Yoshi Says:

    the solution is good, for a quick and dirty one. But if someone also asked you to change Jack to Jiack, Kack to Keack, and so on and so on, you would have to add more exceptional cases to your logic, wich would quickly make it rather complicated. consider adding the exceptional cases to the data instead, allowing you to keep the logic as it is:

    prefixes = ['J', 'K', 'L', 'N', 'M', 'N', 'Ou', 'P', 'Qu']

    the rest of the code would be like the original example. This works, and allows you to go in and change other letters without making the code longer or more complicated

  2. Yoshi Says:

    by the way, I know I’m commenting pretty old posts right now, but just in case another python newcomer comes by, I did it anyway. If he learns something from this, it will have been worth it ;-)

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.