Strings Flashcards
Stings
Strings are ordered sequences of characters, using the syntax of either single quotes or double quotes:
- ‘hello’
- “hello”
- ” I don’t do that “
Indexing
Grabbing a single character from a string [use brackets]. Python indexing starts at 0.
h e l l o
0 1 2 3 4
Reverse Indexing
Same as indexing but backwards
h e l l o
0 1 2 3 4
0 -4 -3 -2 -1
Slicing
Allows you grab a subsection of multiple characters
[start:stop:step]
Start - a numerical index from the slice start
Stop - the index you will go up to (but not include)
Step - the size of the “jump” you take
” “
Denotes a string. Used for a string with a contraction word i.e. “I don’t think so”
Escape Sequence
\n = new line
print(‘hello \n world’)
hello
world
\t = tab space
print(‘hello \tworld’)
hello world
Length Function Len()
Len(‘hello’)
5
Len(‘I am)
4
Indexing
mystring = “Hello World”
mystring[0]
H
mystring[2:] #from this character onward
mystring[:3] #go up to that position, but do not include that character
Slicing
[start:stop:step]
mystring[3:6]
mystring[::-1] #Easy trick to reverse a string!!
Slicing is Immutable. True or False?
True
Slicing is immutable. What does that mean?
Once a string is defined it cannot be sliced to redefine part of it.
name = "Sam" name[0] = 'P' #This will give an error because 'str' object does not support item assignment
String Concatination
Adding strings together
x = ‘Hello World’
x + “ it is beautiful outside!”
‘Hello World it is beautiful outside!
letter = ‘z’
letter * 10
‘zzzzzzzzzz’
You can concatinate a number and a string? True or False?
False
Strings are mutable. True or False?
False
How do you create comments in your code?
#