Using in as a Logical Operator The in keyword can also be used to check to see if one string is “ in ” another string The in expression is a logical expression that returns True or False and can be used in an if statement >>> fruit = 'banana ' >>> 'n' in fruit True >>> 'm' in fruit False >>> 'nan' in fruit True >>> if 'a' in fruit : ... print ( 'Found it! ' ) ... Found it! >>>
Splitting and Joining Strings We can split a string into a list of its letters, each as a string, using the built-in list function >>> list ( " SaqibKhan " ) ['S', 'a', 'q', ' i ', 'b', 'K', 'h', 'a', 'n'] >>> We might think the reverse can be achieved using the familiar built-in str function . It just builds a string showing how the list would be printed by Python: >>> str ( list ( " SaqibKhan " )) " ['S', 'a', 'q', ' i ', 'b', 'K', 'h', 'a', 'n'] " >>>
Splitting and Joining Strings We could write a function to do it ourselves: def join_str (List): s = "" for x in List: s += x return s >>> lst = list ( " SaqibKhan " ) >>> join_str (lst) " SaqibKhan " There is a built-in join function: a method on strings. We specify the empty string and we see this: >>> lst = list ( " SaqibKhan " ) >>> "" . join(lst) " SaqibKhan "
Sorting in Lists >>> lst = [ 1 , 2 , 3 , 3 , 2 , 1 , 2 , 1 ] >>> sorted (lst) [ 1 , 1 , 1 , 2 , 2 , 2 , 3 , 3 ] >>> lst [ 1 , 2 , 3 , 3 , 2 , 1 , 2 , 1 ] Another function provided by Python is sorted() . The sorted() function returns a new, sorted version of the list. It leaves the original list unchanged.
What is an iterator? Why list () is needed to convert the result of map into a list? It is because map returns an iterator not a list. An iterator is something which can be used to range over a data structure. It does not return a list – it returns items one by one. The individual items are not created until they are needed.
Exercise 7-1 Use the sort method to build a function which returns an alphabetically sorted list of all the words in a given sentence.
Exercise 7-2 Write a function to remove spaces from the beginning and end of a string representing a sentence by converting the string to a list of its letters, processing it, and converting it back to a single string. You might find the built-in reverse method on lists useful, or another list-reversal mechanism.
Summary String type Read/Convert Indexing strings [] Slicing strings [ 2 :4] Looping through strings with for and while Concatenating strings with + String operations String comparisons Searching in strings Replacing text Stripping white space List methods List comprehensions