Download presentation
Presentation is loading. Please wait.
1
CHAPTER 3: String And Numeric Data In Python
COMPUTER PROGRAMMING SKILLS
2
Outline String Constants Special Characters String Operations
Types of Numeric Data Hexadecimal, Octal and Binary Numeric Operators and functions Order of Numeric Operators Exercises
3
String Constants Strings are a collection of characters which are stored together to represent arbitrary text inside a python program. You can create a string constant inside a python program by surrounding text with either single quotes (’), double quotes ("), or a collection of three of either types of quotes (’’’ or """). In the first two cases, the opening and closing quotes must appear on the same line in your program; when you use triple quotes, your text can span as many lines as you like. The empty string '' is the string equivalent of the number 0. It is a string with nothing in it.
4
String Constants s = 'Hello' t = "Hello"
m = """This is a long string that is spread across two lines.""" b=''
5
Special Characters The backslash, \, is used to get certain special characters, called escape characters, into your string. There are a variety of escape characters, and here are the most useful ones: \n the newline character. It is used to advance to the next line. \t This is used to insert an escape character. print('Hi\nthere!') print('Hi\t there!') Hi there! Hi there!
6
Special Characters \' for inserting apostrophes into strings. Say you have the following string: s = 'I can't go' This will produce an error because the apostrophe will actually end the string. You can use \' to get around this: s = 'I can\'t go' Another option is to use double quotes for the string: s =" I can't go" \" analogous to \' \\ This is used to get the backslash itself. For example: filename = 'c:\\programs\\file.py' filename = 'c:\\programs\\file.py' print(filename) c:\programs\file.py
7
String Operations (length, concatenation)
To get the length of a string (how many characters it has), use the built-in function len. For example, len('Hello') is 5. The operators + and * can be used on strings. The + operator combines two strings. This operation is called concatenation. The * repeats a string a certain number of times. print('AB'+'cd’) print('A'+'7'+'B’) print('Hi'*4) ABcd A7B HiHiHiHi
8
String Operations (Indexing)
We will often want to pick out individual characters from a string. Python uses square brackets to do this. The table below gives some examples of indexing the string s='Python'. The first character of s is s[0], not s[1]. Remember that in programming, counting usually starts at 0, not 1. Negative indices count backwards from the end of the string. When we try to do s[12]. There are only six characters in the string and Python will raise the following error message: IndexError: string index out of range
9
String Operations (Slices)
A slice is used to pick out part of a string. It behaves like a combination of indexing and the range function. Below we have some examples with the string s='abcdefghij'. index: letters: a b c d e f g h i j
10
String Operations (Changing individual characters of a string)
Suppose we have a string called s and we want to change the character at index 4 of s to 'X'. It is tempting to try s[4]='X', but that unfortunately will not work. Python strings are immutable, which means we can’t modify any part of them. If we want to change a character of s, we have to instead build a new string from s and reassign it to s. Here is code that will change the character at index 4 to 'X’: s = s[:4] + 'X' + s[5:] The idea of this is we take all the characters up to index 4, then X, and then all of the characters after index 4.
11
String Operations (String Methods)
Strings come with a ton of methods, functions that return information about the string or return a new string that is a modified version of the original. Here are some of the most useful ones:
12
String Operations (String Methods)
One very important note about lower, upper, and replace is that they do not change the original string. If you want to change a string, s, to all lowercase, it is not enough to just use s.lower(). You need to do the following: s = s.lower() If you try to find the index of something that is not in a string, Python will raise an error. For instance, if s='abc' and you try s.index('z'), you will get an error.
13
Types of Numeric Data Integers and decimal numbers are represented differently on computers. Integers are whole numbers, which means they have no fractional parts, and they can be positive, negative, or zero. To compute the area of a circle given the circle’s radius, we use the value π, or approximately Python supports such noninteger numbers, and they are called floating-point numbers. The Python name for the floating-point type is float. x = 5 y=5.24 print(type(x)) print(type(y)) <class 'int'> <class 'float'>
14
Hexadecimal, Octal and Binary
Hexadecimal, octal, and binary Python has built-in functions hex, oct, and bin for converting integers to hexadecimal, octal, and binary. The int function converts those bases to base 10. Hexadecimal values are prefaced with 0x, octal values are prefaced with 0o and binary values are prefaced with 0b. print(hex(250)) print(oct(250)) print(bin(250)) print(int(0xfa)) 0xfa 0o372 0b 250
15
Hexadecimal, Octal and Binary
The int function has an optional second argument that allows you to specify the base you are converting from. print(int('101101', 2)) # convert from base 2 print(int('617052', 8)) # convert from base 8 print(int('12A04', 16)) # convert from base 16 45 204330 76292
16
Numeric Operators and functions (operators)
Here is a list of the common operators in Python:
17
Numeric Operators and functions (operators)
The integer division operator, //, is basically, for positive numbers. It behaves like ordinary division except that it throws away the decimal part of the result. For instance, while 8/5 is 1.6, we have 8//5 equal to 1. The modulo operator, %, returns the remainder from a division. For instance, the result of 18%7 is 4 because 4 is the remainder when 18 is divided by 7. Thus to check if a number, n, is even, see if n%2 is equal to 0. To check if n is divisible by 3, see if n%3 is 0.
18
Numeric Operators and functions (functions)
Python has a module called math that contains familiar math functions, including sin, cos, tan, exp, log, log10, factorial, sqrt, floor, and ceil. There are also the inverse trig functions, hyperbolic functions, and the constants pi and e. from math import sin, pi print('Pi is roughly', pi) print('sin(0) =', sin(0)) Pi is roughly sin(0) = 0.0
19
Numeric Operators and functions (functions)
There are two built in math functions, abs (absolute value) and round that are available without importing the math module. The round function takes two arguments: the first is the number to be rounded and the second is the number of decimal places to round to. The second argument can be negative. print(abs(-4.3)) print(round(3.336, 2)) print(round(345.2, -1)) 4.3 3.34 350.0
20
Numeric Operators and functions (functions)
The built-in int function creates an actual integer object from a string that looks like an integer, and the str function creates a string object from the digits that make up an integer. the result of the expression is very different from '5' + '10'. The plus operator splices two strings together in a process known as concatenation. Mixing the two types directly is not allowed: print ('5'+10) #You have to write: print (int('5')+10) or print ('5'+'10') Traceback (most recent call last): File "/home/main.py", line 1, in <module> print ('5'+10) TypeError: Can't convert 'int' object to str implicitly
21
Numeric Operators and functions (functions)
Python comes with a module, called random, that allows us to use random numbers in our programs. To load this function, we use the following statement: from random import randint Using randint is simple: randint(a,b) will return a random integer between a and b including both a and b. from random import randint x = randint(1,10) print('A random number between 1 and 10: ', x) A random number between 1 and 10: 7
22
Order of Numeric Operators
1 ( ) 2 ** 3 / // % 4
23
Exercises Write a program that asks the user to enter a string. The program should then print the following: The total number of characters in the string The string repeated 10 times The first character of the string (remember that string indices start at 0) The first three characters of the string The last three characters of the string The string backwards The second character of the string if the string is long enough The string with its first and last characters removed
24
Exercises Write a program that generates a random number, x, between 1 and 50, a random number y between 2 and 5, and computes x y . Write a program that generates a random number between 1 and 10 and prints your name that many times. Write a program that asks the user to enter two numbers, x and y, and computes |x-y|/(x+y) . Write a program that asks the user for a number and prints out the factorial of that number. Write a program that asks the user for a number of seconds and prints out how many minutes and seconds that is. For instance, 200 seconds is 3 minutes and 20 seconds. [Hint: Use the // operator to get minutes and the % operator to get seconds.]
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.