You’ve probably seen the “Mocking SpongeBob” meme: a picture of SpongeBob SquarePants, with a caption whose text alternates between upper- and lowercase letters to indicate sarcasm, like this: uSiNg SpOnGeBoB MeMeS dOeS NoT mAkE YoU wItTy. For some randomness, the text sometimes doesn’t alternate capitalization.
This short program uses the upper() and lower() string methods to convert your message into “spongecase.” The program is also set up so that other programs can import it as a module with importspongecase and then call the spongecase.englishToSpongecase() function.
tHe PrOgRaM iN AcTiOn
When you run spongecase.py, the output will look like this:
sPoNgEcAsE, bY aL sWeIGaRt [email protected]
eNtEr YoUr MeSsAgE:
> Using SpongeBob memes does not make you witty.
uSiNg SpOnGeBoB MeMeS dOeS NoT mAkE YoU wItTy.
(cOpIed SpOnGeTexT to ClIpbOaRd.)
hOw It WoRkS
The code in this program uses a for loop on line 35 to iterate over every character in the message string. The useUpper variable contains a Boolean variable to indicate if the character should be made uppercase (if True) or lowercase (if False). Lines 46 and 47 toggle the Boolean value in useUpper (that is, set it to its opposite value) in 90 percent of the iterations. This means that the casing almost always switches between upper- and lowercase.
1. """sPoNgEcAsE, by Al Sweigart [email protected]
2. Translates English messages into sPOnGEtExT.
3. View this code at https://nostarch.com/big-book-small-python-projects
4. Tags: tiny, beginner, word"""
6. import random
9. import pyperclip # pyperclip copies text to the clipboard.
10. except ImportError:
11. pass # If pyperclip is not installed, do nothing. It's no big deal.
14. def main():
15. """Run the Spongetext program."""
16. print('''sPoNgEcAsE, bY aL sWeIGaRt [email protected]
18. eNtEr YoUr MeSsAgE:''')
19. spongetext = englishToSpongecase(input('> '))
25. print('(cOpIed SpOnGeTexT to ClIpbOaRd.)')
27. pass # Do nothing if pyperclip wasn't installed.
30. def englishToSpongecase(message):
31. """Return the spongetext form of the given string."""
32. spongetext = ''
33. useUpper = False
35. for character in message:
36. if not character.isalpha():
37. spongetext += character
40. if useUpper:
41. spongetext += character.upper()
43. spongetext += character.lower()
45. # Flip the case, 90% of the time.
46. if random.randint(1, 100) <= 90:
47. useUpper = not useUpper # Flip the case.
48. return spongetext
51. # If this program was run (instead of imported), run the game:
52. if __name__ == '__main__':
ExPloRiNg tHe PrOgRaM
Try to find the answers to the following questions. Experiment with some modifications to the code and rerun the program to see what effect the changes have.
What happens if you change random.randint(1, 100) on line 46 to random.randint(80, 100)?
What happens if you delete or comment out useUpper = not useUpper on line 47?