# String functions

Some string manipulation functions…and some miscellaneous ones…

A function to return the word representation of an integer input:

```def word(n):
"""
pre: n +ve integer
pre: n <= 1000
returns: n in words (English)
"""
wdList = &#91;"one", "two", "three", "four", "five", "six", "seven", "eight", \
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", \
"sixteen", "seventeen", "eighteen", "nineteen", "twenty"&#93;
wdListTens = &#91;"ten", "twenty", "thirty", "forty", "fifty", "sixty", \
"seventy", "eighty", "ninety"&#93;
if n <= 20:
wd = wdList&#91;n - 1&#93;
elif n < 100:
wdTens = wdListTens&#91;n/10 -1&#93;
remTen = n % 10
if remTen != 0:
wdOnes = wdList&#91;n % 10 -1&#93;
else:
wdOnes = ''
wd = wdTens + wdOnes
elif n < 1000:
wdHundreds = wdList&#91;n/100 - 1&#93; + 'hundred'
rem = n % 100
if rem == 0:
wd = wdHundreds
else:
wd = wdHundreds + 'and' + word(rem)
elif n == 1000:
wd = "onethousand"
return wd&#91;/sourcecode&#93;

A palindrome test:
&#91;sourcecode language='python'&#93;def is_palindrome(string):
"""
pre: string any valid string
returns: true if string a palindrome, false otherwise
"""
x = len(string)
for i in range(x/2):
if string&#91;i&#93; != string&#91;x - (i + 1)&#93;:
return False
return True&#91;/sourcecode&#93;

Permutations of a word:
&#91;sourcecode language='python'&#93;def permutations(word):
"""
pre: word a string, len(word)>=1
returns: a list of all permutations of the word
"""
if len(word)==1:
return [word]
else:
result=[]
for i in range(len(word)):
rem = word[:i] + word[i+1:]
for bit in permutations(rem):
result.append(word[i:i+1] + bit)
return result```

Converts an integer to a binary string representation:

```def binary(n):
"""
pre: n +ve integer
returns: binary str repr of n
"""
result = ''
while (n > 0):
result = str(n % 2) + result
n = n/2
return result```

## 2 thoughts on “String functions”

1. Bryce says:

Your is_palindrome is a good one to prove you understand the concept of how to figure out if a string is a palindrome. However, you can make it a bit smaller.

def is_palindrome(string):
if string == string[::-1]:
return True

return False

• Bryce says:

Sorry for the formatting. Not sure how to do a code wrapper on your website. ðŸ˜¦