-
Notifications
You must be signed in to change notification settings - Fork 0
/
sentenceWrap.py
40 lines (30 loc) · 999 Bytes
/
sentenceWrap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
__author__ = 'kathan'
def getWordFromString(str, startIndex):
temp = ''
while startIndex < len(str):
if str[startIndex] == ' ':
break
temp += str[startIndex]
startIndex += 1
return temp
def wrapSentence(str, line_length):
if len(str) < line_length:
return str
length_so_far = 0
result = ''
i = 0
while i < len(str):
word = getWordFromString(str, i)
if len(word) <= line_length:
if len(word) + length_so_far + 1 <= line_length:
length_so_far += len(word) + 1
else:
result += '\n'
length_so_far = len(word) + 1
result += word + " "
i += len(word) + 1
else:
raise Exception('Line length is smaller than the longest word "{}"'.format(word))
print result
str = "A very long string containing many many words and characters. Newlines will be entered at spaces."
wrapSentence(str, 30)