#string stuff
#The basic move: looping through a string with for. This function prints
#all the characters in s, one per line.
def printchars(s):
for c in s:
print(c)
#An equivalent version uses the indices instead.
def printchars2(s):
for j in range(len(s)):
print(s[j])
#return the number of occurrences of
#a particular character in a string
def count_occurrences(s,ch):
count=0
for c in s:
if c==ch:
count+=1
return count
#Note that this computation, like many of the
#others we show here, can be shortened by using
#some of the built-in string functions. In this
#case, count_occurrences(s,ch) is equivalent to
#s.count(ch). Try it!
#This next problem has a one-line solution with the
#built-in string function lower. Here we code it in
#detail from scratch. The function returns a string
#in which every upper-case letter of the argument s
#is replaced by the lower-case equivalent.
def convert_to_lower(s):
gap=ord('a')-ord('A') #always equal to 32, by the way
newstring=''
for c in s:
if('A'<=c<='Z'):
newstring+=chr(ord(c)+gap)
else:
newstring+=c
return newstring
def deleteVowels(s):
newstring=''
for c in s:
if not c in 'aeiouAEIOU':
newstring+=c
return newstring
#Many, many ways to find the reverse a string. This does some arithmetic
#with string indices to get the job done.
def reverse(s):
newstring=''
length=len(s)
for j in range(length):
newstring+=s[length-j-1]
return newstring
#Another method uses the 'for c in s' idiom,
#successively prepending each character to the
#new string.
def reverse2(s):
newstring=''
for c in s:
newstring=c+newstring
return newstring
def ispalindrome(s):
s=s.lower()
#remove non-letters
t=''
for c in s:
if c.isalpha():
t+=c
return t==reverse(t)
#Remove all duplicated characters from a string
def no_duplicates(s):
newstring=''
for c in s:
if not c in newstring:
newstring+=c
return newstring
#Make a nice design from the letters of a string,
#rotating it one character in each line.
def design(s):
for j in range(len(s)):
t=s[j:]+s[:j]
print(t)