Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Strings in Python

Data types and operators

Variables and Types


Variables need no declaration >>> a=1 >>> As a variable assignment is a statement, there is no printed result >>> a 1 Variable name alone is an expression, so the result is printed

Variables and Types


Variables must be created before they can be used

>>> b Traceback (innermost last): File "<interactive input>", line 1, in ? NameError: b >>>

Assignment versus Equality Testing


Assignment performed with single = Equality testing done with double = (==
! "ensible type promotions are defined ! #dentity tested with is operator$

>>> 1==1 1 >>> 1 !==1 1 >>> "1"==1 !

Simple Data Types


"trings
! %ay hold any data, including embedded &'((s ! )eclared using either single, double, or triple quotes >>> s = ""i t#ere" >>> s $"i t#ere$ >>> s = "Embe%%e% $&uote$" >>> s "Embe%%e% $&uote$"

Simple Data Types


! *riple quotes useful for multi+line strings >>> s = """ a lon' strin' (it# "&uotes" or an)t#in' else""" >>> s $ a lon'*!1+strin' (it# "&uotes" or an)t#in' else$ >>> len(s) ,-

Simple Data Types


#nteger ob,ects implemented using - longs
! (i.e -, integer division returns the floor >>> -.+ +

/loat types implemented using - doubles


! &o point in having single precision since execution overhead is large anyway

Simple Data Types


(ong #ntegers have unlimited si0e
! (imited only by available memory >>> lon' = 1/ << 0, >>> lon' 11 +12-345!2-3+!31!!4+23-!+15!0103--+11,0!+5!,-++ 2-00-+5033,5!,10!54+++135+-54!0,!--!!++30+!403 20-50/

Variables and Types


1b,ects always have a type >>> t)pe(1) <t)pe $int$> >>> t)pe(""ello") <t)pe $strin'$> >>> t)pe(1 !) <t)pe $6loat$>

10

Strings vs. Integers


2oth strings and integer variables can store numbers
my_speed_str="300" my_speed_integer=300

34 5hat is the difference between strings and integers6

11

Strings in use
34 5here are strings displayed and entered6

12

String composition
"trings are a composite data type
! ! ! ! 2uilt from another data type, characters #n a string, characters are stored in sequence$ "trings can be any length (including empty $ "tring are enclosed in quotation mar.s$
str_var = "300 m/s" empty_str=""

13

Length o a string
'se len(str) to return string length (7 of characters
sample="SERIES" len(sample)=6 empty_str="" len(empty_str) = 0

14

String representation
#n strings, characters are accessed by inde!
! 8li.e mailboxes in an apartment building$ ! /irst index is 9, not :$
s="LE EL" start!"ar=s# 0$ %&st_v=ss# 2 $

! ;ython strings are immutable "can<t change individual chars


s#0$="'"

15

#perations$ %oncatenation
-ombine strings using & (concatenation operator
(&ll_name = ")enry" * " " * "+ames" print "," * (&ll_name * ","

-oncatenation is not addition


visi-n_str=".0"*".0" =4.0.05 visi-n_val=.0*.0
=30

Try it out$ 2uild a string


/&ild="" 0"ile len(/&ild)12, /&ild = /&ild *"a" print /&ild
16

#perations$ Traversing through a string


'se a loop to examine each character in a string
(-r in strng="6-&nt 7 -( &s" inde8=0 6-&nt=0 0"ile inde8 1 len(strng), i( strng#inde8$ == "&4 -r strng#inde8$ == 49",
6-&nt*=:

inde8*=:

*ry it out ! =ow would we traverse bac.wards6

17

String operations$ ind


(ind() searches for a string within a string *o use it, insert this at the top of your code4
imp-rt string

(ind() returns the first index of a substring


(&ll_name = ")enry +ames" string;(ind((&ll_name<"e")

>ou can specify the starting point of the search4


string;(ind((&ll_name<"e"<.)

#f the string is not found, (ind() returns +: (ind() is case sensitive

18

'igh Level Data Types


List
(ists hold a sequence of items
! %ay hold any ob,ect ! )eclared using square brac.ets

>>> >>> >>> >>> +

l = 789 :n empt) list l appen%(1) l appen%(""i t#ere") len(l)

19

'igh Level Data Types


>>> l 71, $"i t#ere$8 >>> >>> l = 7""i t#ere", 1, +8 >>> l 7$"i t#ere$, 1, +8 >>> l sort() >>> l 71, +, $"i t#ere$8

20

'igh Level Data Types


Tuple
*uples are similar to lists
! "equence of items ! ?ey difference is they are immutable ! 1ften used in place of simple structures

Automatic unpac.ing >>> point = +,2 >>> ;, ) = point >>> ; +

21

'igh Level Data Types


*uples are particularly useful to return multiple values from a function >>> ;, ) = <et=oint() As ;ython has no concept of byref parameters, this technique is used widely

22

'igh Level Data Types


Dictionary
)ictionaries hold .ey+value pairs
! 1ften called maps or hashes$ #mplemented using hash+tables ! ?eys may be any immutable ob,ect, values may be any ob,ect ! )eclared using braces

>>> %=>? >>> %7!8 = ""i t#ere" >>> %7"6oo"8 = 1

23

'igh Level Data Types


)ictionaries (cont$

>>> >>> + >>> $"i

% = >! : ""i t#ere", 1 : ""ello"? len(%) %7!8 t#ere$

24

#perators

25

#perators
;ython has many operators$ "ome examples are4 *< =< >< /< ?< @< 1< == print 1perators perform an action on one or more operands$ "ome operators accept operands before and after themselves4 -perand: * -perand., or 3 * 2 1thers are followed by one or more operands until the end of the line, such as4 print 4)iA5< 3.< 3B 5hen operators are evaluated, they perform action on their operands, and produce a new value$
26

E!ample E!pression Evaluations


An expression is any set of values and operators that will produce a new value when evaluated$ =ere are some examples, along with the new value they produce when evaluated4 2 * :0 produces :@ 4)i5 * 4 4 * 4+ayA5 produces A=i BayCD :0 / (.*3) produces E :0 @ 2 produces *rue :0 1 2 produces /alse :0 / 3;2 produces E$F@G:HEF@G: :0 / 3 produces I :0 ? 3 produces :
27

List o #perators$ &( )( *( +( ,( -( ,.( -.( ..( /


"ome operators should be familiar from the world of mathematics such as Addition (J , "ubtraction (+ , %ultiplication (K , and )ivision (L $ ;ython also has comparison operators, such as (ess+*han (M , Nreater+*han (O , (ess+*han+or+ Equal(M= , Nreater+*han+or+Equal (O= , and Equality+*est (== $ *hese operators produce a *rue or /alse value$ A less common operator is the %odulo operator (P , which gives the remainder of an integer division$ :9 divided by I is Q with a remainder of :4 :0/3 produces I, while :0?3 produces :
28

DA01E23 #perator #verloading3


&1*EC "ome operators will wor. in a different way depending upon what their operands are$ /or example, when you add two numbers you get the expected result4 3 * 3 produces R$ 2ut if you AaddD two or more strings, the J operator produces a concatenated version of the strings4 4)i5 * 4+ay5 produces A=iBayD %ultiplying strings by a number repeats the stringC 4)i +ay5 > 3 produces A=i Bay=i Bay=iBayD *he modulo operator also wor.s differently with strings4 4test ?(5 ? 33 produces Atest IH$999D
29

Type %onversion
int() 6loat() str() Examples4 int(3;3) produces I str(3;3) produces AI$ID

(l-at(3) produces I$9 (l-at(43;25) produces I$@ int(4C5) produces G int(4C;:5) throws an ESS1SC (l-at(4Dest5) *hrows an ESS1SC
30

Variables
Variables are names that can point to data$ *hey are useful for saving intermediate results and .eeping data organi0ed$ *he assignment operator (= assigns data to variables$
)onTt confuse the assignment operator (single equal sign, = with the Equality+*est operator (double equal sign, ==

Variable names can be made up of letters, numbers and underscores (U , and must start with a letter$

31

Variables
5hen a variable is evaluated, it produces the value of the data that it points to$ /or example4 my aria/le = 2 my aria/le produces @ my aria/le * :0 produces :@ >ou %'"* assign something to a variable (to create the variable name before you try to use (evaluate it$

32

Program E!ample
/ind the area of a circle given the radius4 Radi&s = :0 pi = 3;:3:2E area = pi > Radi&s > Radi&s print area will print I:H$:@ to the screen$

33

Keywords, Name-spaces & Scope


&ames that are defined in a function are AlocalD to that function$

&ames that are defined outside of a function are AglobalD to the module$

(ocal names overshadow global names when inside the function that defined them$

#f you want to access a global variable from inside of a function, you should declare it AglobalD$

34

1lobal vs Local e!ample


my aria/le = C myFaram = .0 de( (&n6:(myFaram), my aria/le = .0 print myFaram (&n6:(2) print my aria/le 5hat gets printed6

35

1lobal vs Local e!ample


my aria/le = C myFaram = .0 de( (&n6:(myFaram), gl-/al my aria/le my aria/le = .0 print myFaram (&n6:(2) print my aria/le 5hat gets printed6 @ and E9 *he AlocalD myVariable inside func: is separate from the AglobalD myVariable outside of func: *he function assigns E9 to the AglobalD myVariable, overwriting the G before it gets printed$
36

You might also like