Characters in string manipulation


#1



I am trying to rearrange the characters in a string. How do i do this? Is there a way to move them around? Thanks.


Replace this line with your code.


#2

In a string, not recommended, but it can be converted to a list of characters with list(). Then the list can be manipulated anyway we wish. When we're done, join() it back up and it's a string again.


#3

I am trying to convert a word from English to Pig Latin. This involves taking the first letter of user input and putting it at the end, then adding letters 'ay' to end. Here is code I have so far.

def PigLatin():
print "Welcome to the Pig Latin translator"
print "Input a word in English"
what_the_user_input = raw_input("Type in word and hit 'Enter'.")
if type(what_the_user_input) == string:
return "This is a string!"
else:
return "This is not a string!"
tail = what_the_user_input(1:)


#4

raw_input() returns Unicode, not string type. Checking the type on raw input is not a very reliable test. That's why we have .isalpha() to check for actual word characters.

pyg = "ay"
original = raw_input("Enter a word to translate...")
if len(original) > 0 and original.isalpha():
    # we know we have text of word characters so we can use string tools on it
    word = original.lower()

In this exercise we never actually manipulate the string, only use slices of it to form a new one.

first = word[0]
new_word = word + first + pyg
new_word = [1:len(new_word)]
print new_word

In many languages, strings are to be treated as immutable (even while we have the tools to mutate them). That's why we cast a new one along side, or work from a list copy of the string.