CMU Coding Bootcamp
1def wrapText(text: str, lineSize: int) -> str:
2 """Wrap text to a specified line size."""
3 lines = []
4 words = text.split()
5 currentLine = ""
6 for word in words:
7 if len(currentLine) + len(word) > lineSize:
8 currentLine = currentLine.rstrip()
9 currentLine = currentLine.ljust(lineSize)
10 currentLine = f"|{currentLine}|"
11 lines.append(currentLine)
12 currentLine = f"{word} "
13 else:
14 currentLine += f"{word} "
15 else:
16 currentLine = currentLine.rstrip()
17 currentLine = currentLine.ljust(lineSize)
18 currentLine = f"|{currentLine}|"
19 lines.append(currentLine)
20 return "\n".join(lines)
21
22
23print("Testing wrapText()...", end="")
24text = """\
25This is some sample text. It is just sample text.
26Nothing more than sample text. Really, that's it."""
27
28textWrappedAt20 = """\
29|This is some sample |
30|text. It is just |
31|sample text. Nothing|
32|more than sample |
33|text. Really, that's|
34|it. |"""
35
36assert wrapText(text, 20) == textWrappedAt20
37
38textWrappedAt30 = """\
39|This is some sample text. It |
40|is just sample text. Nothing |
41|more than sample text. Really,|
42|that's it. |"""
43
44assert wrapText(text, 30) == textWrappedAt30
45
46textWrappedAt40 = """\
47|This is some sample text. It is just |
48|sample text. Nothing more than sample |
49|text. Really, that's it. |"""
50
51assert wrapText(text, 40) == textWrappedAt40
52print("Passed!")