$ python >>> help(str) >>> help(list)
s = "hello there" length = len(s) print(length) # prints 11 (space is a character) print(s[0]) # prints h print(s[1]) # prints e
Because a string is a sequence, we can use it in a for loop. We can either iterate over each character in the string, or each position in the string. Here are two examples:
s = "hello" for ch in s: # iterate over each character in the string print(ch) for i in range(len(s)): # iterate over positions (i.e., 0, 1, 2, ...) print(s[i])
You can convert from one type to another (if possible) using str(), int(), and float():
s = str(1234) # convert int value to a string "1234" x = int(s) # convert "1234" to an int f = float(s) # convert "1234" to a float (1234.0)
Strings are immutable, which means you cannot change individual characters in a string. However, you can create new strings from parts of existing strings. Slicing (using [:] to pick out part of the original string) and concatenation (using the + operator) are useful for doing this:
>>> s = "swarthmore computer science" >>> slice = s[11:15] >>> print(slice) comp >>> slice = slice + "sci" >>> print(slice) compsci >>>
Here's an example of using concatenation to accumulate a string:
s = "" # start with empty string for i in range(5): s = s + str(i) # add to it print(s) # prints the string "01234"You can test if a substring is present in another string using the in (membership) operator:
"a" in "computer science" # evaluates to False "the" in "hello there" # evaluates to True "LL" in "hello there" # evaluates to False
'0' < '8' # True 'a' < 'b' # True 'C' < 'Z' # True 'a' < 'Z' # False (ascii encoding for 'a' is larger than 'Z') "aaa" < "bbb" # True "aaabc" < "aabb" # True : 1st two characters ==, but third 'a' < 'b' so TrueWith single character strings you can convert to their ascii values. The ascii values alone are not that useful, but comparing them can often be. Remember that the encodings for 'a' to 'z', 'A' to 'Z' and '0' to '9' are contiguous:
>>> ch = "C" >>> ord(ch) 67 # "C" is ascii value 67 >>> ord("A") 65 # "A" is ascii value 65 >>> ord(ch) - ord("A") 2 # difference tells us position of "C" in alphabet >>> nextch = chr(68) # "D" has ascii value 68 >>> print(nextch) D
L = [3, 5, 9, 11] print(len(L)) # prints 4, number of elements in the listBecause a list is a sequence (just like strings) we can iterate using a for loop.
# iterate over elements in list for elm in L: print(elm) # prints out each element in the list # iterate over positions in list for i in range(len(L)): print(L[i]) # prints out item at each position
Python's list() and range() functions are useful in creating lists:
L = list("hello") # create a list of 5 single-character strings ['h','e','l','l','o'] L = range(5) # create a list of integers [0, 1, 2, 3, 4] L = range(0,50,7) # create a list from 0-50 by 7's [0, 7, 14, 21, 28, 35, 42, 49]Unlike strings, lists are mutable, which means that their contents can be modified without having to create a new list.
>>> L = range(5) >>> L[3] = "hello" >>> print(L) [0, 1, 2, 'hello', 4]
The append method can be used to add a new element to the end of a list (growing its length by one):
L = [] # create an empty list for i in range(5): L.append(str(i)) # add str(i) to end of L print(L) # ['0', '1', '2', '3', '4'] print(len(L)) # 5You can test if an element is in a list using the in (membership) operator:
L = range(1,100) 50 in L # evaluates to True 250 in L # evaluates to False "a" in L # evaluates to False
s = "CS21 Rocks!" s2 = s.lower() # s2 gets "cs21 rocks!" all upper-case alpha in s converted to lower ch = 'a' if(ch.isapha()): print("a string of alphabetic chars only") s = "123456" if(s.isdigit()): print("a string of numeric chars only") s = " CS21 Rocks!! \n" s = s.strip() # creates new string from s with leading and trailing whitespace removed print("*%s*" % (s)) # *CS21 Rocks!!* # split string on whitespace s = "we love computer science!" L = s.split() print(L) # ['we', 'love', 'computer', 'science!'] my_list = ["Python", "is", "awesome"] s = "".join(my_list) # create new string from contents of list with "" between each item print(s) # "Pythonisawesome" s = "*".join(my_list) # "Python*is*awesome"
lst = [1, 3, 11] lst.append(8) # add 8 to the end of the list: [1, 3, 11, 8] lst.append(3) # add 3 to the end of the list: [1, 3, 11, 8, 3] i = lst.index(3) # returns 1, the index of the first occurrence of 3 in the list lst.insert(i,5) # insert the value 5 into the list at position i print(lst) # [1, 5, 3, 11, 8, 3] how_many_threes = lst.count(3) # count the number of 3's in the list (2) L = list("ABCDEFG") >>> print(L) ['A', 'B', 'C', 'D', 'E', 'F', 'G'] >>> L.pop() # remove and return last item 'G' >>> print(L) ['A', 'B', 'C', 'D', 'E', 'F'] >>> L.pop() # remove and return last item 'F' >>> print(L) ['A', 'B', 'C', 'D', 'E'] >>>
Often in programs that manipulate strings, you want to convert from str to list or list to str (due to list being mutable and str being immutable). Here are some examples of converting str to list (use the str class join() method (above) to convert a list to str):
# create a list of 1-character strings from a string s = "CS21 Rocks!" lst = list(s) # ['C','S','2','1',' ','R','o','c','k','s','!'] print(len(lst)) # 11 lst = s.split() # ["CS21", "Rocks!"] print(len(lst)) # 2 # use the string split method to create a list of strings from a string s = "You:Can:Split:A:String:on:any====string" slist = s.split("====") print(slist) # ['You:Can:Split:A:String:on:any', 'string'] slist2 = s.split(":") print(slist2) # ['You', 'Can', 'Split', 'A', 'String', 'on', 'any====string']