String Manipulation Part 1
String Manipulation Previously, we saw that we could concatenate strings and perform string repetitions Full_name = “Donald ” + “The Man ” + “Seok” Lyrics = “I know” * 8
String Manipulation We were also able to compare strings, and convert other data types into strings and also count the length of a string if “animal” > “apple”: print(“animal will come before apple in the dictionary”) x = str(43.95) print( len( “Donald” ) )
String Manipulation Sometimes, we will need to access individual characters in a string We can do this by using a for loop, which will iterate the number of times equivalent to the length of a string Through each iteration, your target variable will hold a different character value, in order of the string
String Manipulation for x in “Donald”: print (x) >> D o n a l d
Programming Challenge Write a program that counts the number of “S”s there are in the string: “Sally Sells Seashells By The Sea Shore” Your program should count upper case and lower case “s”s the same way
Updating Strings However, you cannot directly update a string while iterating over it through a for loop Name = “Donald” for x in Name: x = “A” print (Name) >> Donald
Updating Strings You can achieve this task by creating a new variable Name = “Donald” NewName = “” for x in Name: NewName += “A” print(Name, NewName) >> Donald AAAAAA
Indexing We can also analyze individual elements in a string by a method called “indexing” We can call any specific character in a string by calling it’s variable name followed by brackets with an integer denoting the place of the character word = “Donald” print(word[2]) >> n
Indexing Indexes always start with the zero value Therefore the first character in a string can be denoted as the “0th value” The index of the last character is denoted by the length of the string minus one
Indexing # S u p e r m a n # 0 1 2 3 4 5 6 7 word = “Superman” print(len(word)) print(word[0]) >> 8 S
Indexing Negative indexes work backwards So -1 will denote the last character in a string, -2 will denote the second to last character, etc. number = “456” print(number[-1], number[-2], number[-3], sep = “”)
Indexing If you use an integer index value that is greater than the length of the word, you will raise an exception word = “Superman” print(word[10]) # error!
Programming Challenge Define a function that accepts two arguments: a string literal and a single character. Have the function return the number of times you find the specified character within the string literal. Then use the function to ask the user what character they would like to search for in a word / phrase and print out the result
Programming Challenge Write a program that counts the number of vowels found in a particular word / phrase Use your function from the previous challenge
Programming Challenge: Pig Latin In Pig Latin, the first letter of each word is removed and re-attached to the end of the string with the additional “ay” Create a function that converts words into Pig Latin Example: hello ellohay
Programming Challenge Write a program that asks the user for a word and finds the letter that is closest to the end of the alphabet in the string Example: zelda z peach p apple p Write a program that finds the letter closest to the beginning of the function
Min/Max Functions Python has two built in functions that obtain the maximum and minimum characters in a string (based on their ASCII code) Example: a = max(“python”) b = min(“python”) print(“max:”, a) print(“min:”, b) >> max: y min: h
Strings are Immutable As we discussed briefly, strings are an immutable data type, meaning that once they are created, they cannot be changed Although we’ve rewritten variables to hold different values, Python simply points at a separate string in your computer’s memory, then holding that new value name = “Donald” name = “Seok”
Strings are Immutable We saw that we can use indexing to pull out single characters from strings but they weren’t necessarily changing the string, rather we created new ones with the values of the characters we pulled out
Slicing Strings Now, we’ll see how we can extract multiple characters or a portion of a string out at a time We will call this “slicing” Example: full_name = “Donald Seok” first_name = full_name[0:6] print(first_name) >> Donald
Slicing Strings In addition, just like the range function, slicing can be done with a step value as well full_name = “Donald Seok” new = full_name[0:6:2] print(new) >> Dnl
Slicing Strings Just a couple of more notes about slicing strings: - If you omit a starting value, Python will assume that you want to start at the beginning - Similarly, if you omit an end value, it will assume til the end
Practice: Slicing Notation word = “Superman sings in the shower.” print(word[0:8]) print(word[9:14]) print(word[:5]) print(word[9:]) print(word[-7:]) print(word[0:len(word):3)
Practice: Slicing Notation word = “Superman sings in the shower.” print(word[0:8]) # Superman print(word[9:14]) # sings print(word[:5]) # Super print(word[9:]) # sings in the shower. print(word[-7:]) # shower. print(word[0:len(word):3) # Seasgit or
Programming Challenge: Usernames Let’s say you work at the IT department for NYU and you are asked to generate student ID’s for the incoming freshman class ID’s are created as follows: The first four characters of a student’s last name The first character of a student’s first name The last two digits of the year in which they graduated high school
Programming Challenge: Mirror Write a function entitled “mirror” that reverses a word and returns it back to the user
Programming Challenge: RACECAR A palindrome is a word that when spelled backwards is still the same word Write a program that asks the user for a word Determine whether the word is a palindrome