/
Strings and the slice operator Strings and the slice operator

Strings and the slice operator - PowerPoint Presentation

liane-varnes
liane-varnes . @liane-varnes
Follow
373 views
Uploaded On 2018-02-25

Strings and the slice operator - PPT Presentation

The slice operator This is the substring method which most languages have Given a string you can slice pieces of the string the syntax of the operator uses the square brackets s57 means the part of the string s which starts at position 5 and includes everything ID: 635755

statement string slice means string statement means slice position operator expression bcd omitting characters including copy str range colon

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "Strings and the slice operator" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

Slide1

Strings and the slice operatorSlide2

The slice operator

This is the “substring” method which most languages have

Given a string, you can slice pieces of the string

the syntax of the operator uses the square brackets

s[5:7] means the part of the string s which starts at position 5 and includes everything

up to

but not including

position 7, in other words, the characters at position 5 and at position 6

Omitting an argument before the colon means to start at the beginning of the string s[:3] means s[0], s[1] and s[2]

Omitting an argument after the colon means to include the rest of the string s[4:] means s[4], s[5]… up to and including the end of the stringSlide3

slice returns a new

string

Suppose s were “

abcdef

” and you wrote an expression like s[1:4

]

Its value is “

bcd

”, a new string (the original string is not changed at all)

If the expression were on a line by itself, it does nothing!

You need to use the expression IN some statement, like an assignment statement, an if statement, a while statement, a print statement

print(s[1:4])

makes sense

t = s[1:4]

makes a copy of the 3 characters as a string and puts it into t

s = s[1:4]

this does the same as the statement above, but the previous value of s is also discarded

if s[1:4] == “

bcd

”:

would result in TrueSlide4

Be careful of your range

str

[i:i+1] is the same as saying

str

[

i

]

It is possible to go

out of range with slice – don’t go past the end of the

string!

You can leave off both the starting and ending points, as in

s[:].

This produces a copy of the whole string.