Presentation is loading. Please wait.

Presentation is loading. Please wait.

Strings and the slice operator

Similar presentations


Presentation on theme: "Strings and the slice operator"— Presentation transcript:

1 Strings and the slice operator

2 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 string

3 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 True

4 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.


Download ppt "Strings and the slice operator"

Similar presentations


Ads by Google