Presentation is loading. Please wait.

Presentation is loading. Please wait.

Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.

Similar presentations


Presentation on theme: "Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1."— Presentation transcript:

1 Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1

2 If you have the old book! This chapter is the one with most differences between: – the new and the old book, – 3.2 and 2.7 Python – The differences are in the string formatting that we show at the end of the slides. 2

3 Overview String objects: – What are they? – How to create them? – They are immutable. Element/character access Comparing strings: lexicographic order String operators: +, * Converting str objects to and from other types String methods – Find, index, in The ASCII code Strings with special characters String formatting 3

4 String objects Words, sentences and whole phrases can be stored as string objects. Creating strings – Using single or double quotes: 'These', " are ", """string objects. """ Double quotes are better than single : “ Bob’s” vs ‘Bob’s’ The triple quotes preserve formatting (new lines). You can use them for longer comments. – Using the str constructor: str(123), str([1,2,3]) String operators: +, * – Strings can be concatenated together with + >>> 'This' + ' is a ' + ' new string.' – String repetitions: >>> ' apple ' * 3 >>> ' apple ' * 0 4

5 Strings: element access Individual elements: >>> my_str = "Lovely" >>> my_str[0] >>> my_str[5] Slicing: >>> my_str[::2] # a string formed from every other letter >>> my_str[::-1] # a copy of the string in reversed order Iterate over a string with a for loop len function gives the length of a string >>> len(my_str) 5

6 The in Operator >>> a = [1, 2, 3] >>> 2 in a True >>> 5 in a False >>> vowels = "aeiou" >>> "a" in vowels True >>> "k" in vowels False 6 The in operator works for lists and strings. Syntax: element in container Returns true if the element appears in the container, false otherwise.

7 upper and lower 7 >>> vowels = "aeiou" >>> b = vowels.upper() >>> vowels 'aeiou' >>> b 'AEIOU' >>> a = " New York City " >>> b = a.lower() >>> b 'new york city' The string.upper() method returns a new string where all letters are upper case. The string.lower() method returns a new string where all letters are lower case. Note: upper() and lower() do not modify the original string, they just create a new string. Should be obvious, because strings cannot be modified.

8 index and find 8 >>> my_str = "this is crazy" >>> my_str.index("is") 2 # is this correct? >>> my_str.index("q") error >>> my_str.find("is") 2 >>> my_str.find("q") The my_list.index(X) method returns the first position where X occurs in the string. Gives an error if X is not in my_list. The my_string.find(X) method returns the first position where X occurs in the string. X can be a single letter or more letters. Returns -1 if X is not found.

9 String Comparisons >>> my_strings = ["abc", "ABC", "Abc", "abcd", "acd", "a","A", "c","C"] >>> my_strings ['abc', 'ABC', 'Abc', 'abcd', 'acd', 'a', 'A', 'c', 'C'] >>> my_strings.sort() >>> my_strings ['A', 'ABC', 'Abc', 'C', 'a', 'abc', 'abcd', 'acd', 'c'] Python uses the lexicographic (dictionary) order for strings. Capital letters are always before lower case letters. 9

10 String Comparisons It is easy to verify the order that Python uses, by trying out different pairs of strings. >>> "hello" < "goodbye" False >>> "Hello" < "goodbye" True >>> "ab" > "abc" False 10

11 String Comparisons >>> "123" < "abc" True >>> "123" < "ABC" True Numbers come before letters. Comparing strings of different lengths. – Any prefix of a string is smaller than the string itself. >>> "ab" > "abc" False 11

12 Strings Cannot Change >>> a = "Munday" >>> a[1] = 'o' Traceback (most recent call last): File " ", line 1, in a[1] = 'o' TypeError: 'str' object does not support item assignment 12

13 If You Must Change a String… You cannot, but you can make your variable equal to another string that is what you want. Example: >>> my_string = "Munday" – my_string contains a value that we want to correct. >>> my_string = "Monday" – We just assign to variable my_string a new string value, that is what we want. 13

14 For More Subtle String Changes… Suppose that we want a program that: – Gets a string from the user. – Replaces the third letter of that string with the letter A. – Prints out the modified string. 14

15 For More Subtle String Changes… Strategy: – convert string to list of characters – do any manipulations we want to the list (since lists can change) – convert list of characters back to a string Using a loop. Using the join method for strings. – joining_string.join(list_of_strings) – >>> " - ".join([1,2,3]) 15

16 Write a program that: – Gets a string from the user. – Modifies that string so that position 3 is an A. – Prints the modified string. 16 An Example

17 An Example: with loop my_string = input("please enter a string: ") if (len(my_string) >= 3): # convert string to list, make the desired change (change third letter to "A") my_list = list(my_string) my_list[2] = "A"; # create a string out of the characters in the list new_string = "" for character in my_list: new_string = new_string + character my_string = new_string # assign the my_string variable to the new string object print("the modified string is ", my_string) 17

18 An Example: with join my_string = input("please enter a string: ") if (len(my_string) >= 3): # convert string to list, make the desired change (change third letter to "A") my_list = list(my_string) my_list[2] = "A"; # create a string out of the characters in the list new_string = "".join(my_list) my_string = new_string print("the modified string is ", my_string) 18

19 An Example: with slicing and + my_string = input("please enter a string: ") my_string = my_string[0:2] + "A" + my_string[3:] print("the modified string is ", my_string) 19

20 Converting Other Types to Strings 20 >>> a = 2012 >>> b = str(a) >>> b '2012' >>> a = ['h', 'e', 'l', 'l', 'o'] >>> b = str(a) >>> b "['h', 'e', 'l', 'l', 'o']" >>> "".join(a) 'hello' >>>" ".join(a) 'h e l l o' The str function converts objects of other types into strings. Note: str does NOT concatenate a list of characters (or strings). See example on left. We can use the join method. It concatenates the elements in the list, separating them with the string that it is called on. Here: "" and " ".

21 Converting Strings Into Ints/Floats 21 >>> a = '2012' >>> b = int(a) >>> b 2012 >>> float(a) 2012.0 >>> a = "57 bus" >>> int(a) The int, float functions converts strings to integers and floats. Will give error message if the string does not represent an integer or float.

22 Converting Strings Into Lists 22 >>> a = "hello" >>> list(a) ['h', 'e', 'l', 'l', 'o'] The list function can convert a string to a list. Always works. Very handy if we want to manipulate a string's contents and create new strings based on them. (Like we did in an earlier example in this lecture)

23 The ASCII code In any string, each letter is represented by a value (the ASCII value): – ord(ch) function returns the numeric ASCII value of a character given as an argument >>> ord(‘a’) >>> ord(‘A’) >>> ord(‘1’) >>> ord(‘.’) – chr(i) function returns the character who’s ASCII code is i. >>> chr(97) 23

24 Strings with special characters >>> import string # this must be run before the following lines >>> string.punctuation '!"#$%&\'()*+,-./:; ?@[\\]^_`{|}~‘ >>> string.digits '0123456789‘ >>> string.whitespace ' \t\n\r\x0b\x0c‘ >>> string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz‘ >>> string.ascii_uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 24

25 Formatted output for strings “format string”.format(data1, data2,…) >>> “{} is {} years old”.format(“Bill”, 25) >>> print(“{} is {} years old”.format(“Bill”, 25)) Formatting commands will give directive about how corresponding data will be printed. – Alignment number:, ^ – Width number – Precision descriptor – Descriptor code s (strings) d (decimal) f (floating point decimal) e (floating point exponential) % (floating point as percent) Syntax: {:[align] [minimum_width] [.precision] [descriptor] } >>> “{:>10s} is {:<10d} years old”.format(“Bill”, 25) >>> “{:8.2%}”.format(2/3) >>> “{:8.2f}”.format(2/3) Where is this usefull? Can you see a use for it? 25

26 List methods You can find a list of the string methods in the Python Library Reference:  Go to: Sequence types – str, bytes,…  http://docs.python.org/release/3.2/library/stdtypes.ht ml#sequence-types-str-bytes-bytearray-list-tuple-range http://docs.python.org/release/3.2/library/stdtypes.ht ml#sequence-types-str-bytes-bytearray-list-tuple-range  scroll down to String Methods A few methods: – upper, lower, title, isupper, islower, istitle 26


Download ppt "Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1."

Similar presentations


Ads by Google