Starting Out With Python - Chapter3 - More About Strings
Starting Out With Python - Chapter3 - More About Strings
More
About
Strings
Topics
Basic String Operations
String Slicing
Testing, Searching, and Manipulating
Strings
Use indexing
Each character has an index specifying its position
in the string, starting at 0
Format: character = my_string[i]
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
String Concatenation
Concatenation: appending one string
to the end of another string
Use the + operator to produce a string that is
a combination of its operands
The augmented assignment operator += can
also be used to concatenate strings
The operand on the left side of the += operator
must be an existing variable; otherwise, an
exception is raised
String Slicing
Slice: span of items taken from a
sequence, known as substring
Slicing format: string[start : end]
Expression will return a string containing a copy of
the characters from start up to, but not including,
end
If start not specified, 0 is used for start index
If end not specified, len(string) is used for end
index
String Methods
Strings in Python have many types of
methods, divided into different types of
operations
General format:
mystring.method(arguments)
replace(substring, new_string):
Returns a copy of the string where every
occurrence of substring is replaced with
new_string
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Splitting a String
split method: returns a list containing
the words in the string
By default, uses space as separator
Can specify a different separator by passing it
as an argument to the split method
Summary
This chapter covered:
String operations, including:
Methods for iterating over strings
Repetition and concatenation operators
Strings as immutable objects
Slicing strings and testing strings
String methods
Splitting a string