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 import
spongecase
and then call the spongecase.englishToSpongecase()
function.
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.)
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 sPOnGEcAsE.
3. This code is available at https://nostarch.com/big-book-small-python-programming
4. Tags: tiny, beginner, word"""
5.
6. import random
7.
8. try:
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.
12.
13.
14. def main():
15. """Run the Spongecase program."""
16. print('''sPoNgEtExT, bY aL sWeIGaRt [email protected]
17.
18. eNtEr YoUr MeSsAgE:''')
19. spongecase = englishToSpongecase(input('> '))
20. print()
21. print(spongecase)
22.
23. try:
24. pyperclip.copy(spongecase)
25. print('(cOpIed SpOnGeCasE to ClIpbOaRd.)')
26. except:
27. pass # Do nothing if pyperclip wasn't installed.
28.
29.
30. def englishToSpongecase(message):
31. """Return the spongecase form of the given string."""
32. spongecase = ''
33. useUpper = False
34.
35. for character in message:
36. if not character.isalpha():
37. spongecase += character
38. continue
39.
40. if useUpper:
41. spongecase += character.upper()
42. else:
43. spongecase += character.lower()
44.
45. # Flip the case, 90% of the time.
46. if random.randint(1, 100) <= 90:
47. useUpper = not useUpper # Flip the case.
48. return spongecase
49.
50.
51. # If this program was run (instead of imported), run the game:
52. if __name__ == '__main__':
53. main()
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.
random.randint(1, 100)
on line 46 to random.randint(80, 100)
?useUpper = not useUpper
on line 47?