PYTHON PROGRAMMING. PART II: PYTHON OBJECTS AND DATA STRUCTURE BASICS. UNIT 3: STRING. PART I: BASICS OF STRING
PYTHON PROGRAMMING
PART II: PYTHON OBJECTS AND DATA STRUCTURE BASICS
UNIT 3: STRING
PART I: BASICS OF STRING
I. Definition
Strings are used to represent and manipulate a sequence of characters.
Example: "Khiem", "Hello World", "Yesterday, all my trouble seems so far away".
II. String basics
1. String indexing and slicing
a) String indexing
We know that strings are sequences of characters so we can use indexes to call parts of the string!
Let s = "John"
We have: s[0] = "J"
s[2] = "h"
s[-1] = "n" (-1 is defined as the last character in the string)
We can also use negative numbers on indexing, as the above example.
b) String slicing:
We use the colon : to slice the string, which grabs everything up to a designated point.
print(s[1:]) # Grab everything past the first term all the way to the length of s which is len(s) => "ohn"
print(s) #Notice that s has no changes.
=> "John"
print(s[:3]) #Grab everything up to the 3rd index, but notably, it does not include the 3rd index.
=> "Joh"
print(s[:]) #Grab everything!
=> "John"
print(s[::-1]) #Grab everything backwards as the stepsize is -1
=> "nhoJ"
print(s[1::2]) #Grab letters from the 1st index and increase by a stepsize of 2.
=> "on"
So keep in mind:
2. String Properties
Comments
Post a Comment