I have to write a spell-check program for school and I have 2 specific quick problems: the first is that I'm trying to write a function that takes 2 adjacent letters of a word and switches them then returns the new word... it goes on to the next to letters and does the same til it reaches the end
this is what I have:
word = 'cat'
index = 0
for c in word:
#while etc. etc.
first_letter = word[index]
new_word = word.replace(word[index], word[index + 1])
new_word[index+1] = word[index]
new_word[index] = word[index+1]
return new_word
index += 1

but it won't let me do the new_word[index] = word[index+1] and give me this error :

Traceback (most recent call last):
File "<string>", line 1, in <string>
TypeError: 'str' object does not support item assignment

The second is that I'm writing a function that removes 1 of any 2 adjacent doubled letters (i.e. latter --> later)

new_string = ''
index = 0
for c in word:
adjacent = word[index + 1]
if c != adjacent:
new_string = new_string + c
index += 1
print new_string

that is what I have and let's say I use 'ccat', I get this back:

c
ca

Thanks a lot!

Cerralife

You can use the step function of a for loop to reverse every pair of two letters. The logic for removing a double letter would be similar.

def switch_letters(word):
   word_list = list(word)
   for j in range(1, len(word), 2):
      word_list[j-1], word_list[j] = word_list[j], word_list[j-1]
   return "".join(word_list)


print switch_letters("cat")
print switch_letters("antidisestablishmentarianism")

If you want to impress your teacher, use this

>>> import re
>>> pat = re.compile(r"\w{2}")
>>> pat.sub(lambda mo: mo.group(0)[-1::-1], "antidisestablishmentarianism")
'naitidestsbailhsemtnraaiinms'
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.