Words and sentences are
collections of characters, and so are Python strings.
You can access any
character in a Python string using its index, either counting from the
beginning or the end of the string. When you
start from the beginning, you count from 0.
In Python integer indices
are zero based.
>>> name = “My Name is Mike”
>>> name[0]
‘M’
>>> name[1]
‘y’
>>> name[9]
‘s’
>>> name[-1]
‘e’
>>> name[-15]
‘M’
>>> name[7]
‘ ‘s
*********************
********************
Slicing
You can take shorter
substrings from inside a longer string.
This operation is called
‘slicing’.
>>> name[11:14] # from 11th to 14th, 14th one is excluded
‘Mik’
>>> name[11:15] # from 11th to 15th, 15th one is excluded
‘Mike’
If you want to check if a
string contains a particular substring, you can use the ‘in’
operator.
>>> “B” in “Foo”
False
>>> “B” not in “Foo”
True
>>> “G” in “Gohl”
True
>>> “James”
in “James
is tall”
True
The len function
calculates the length of a string.
>>> len(name)
15
*********************
********************
Concatenation
In Python it’s possible
to combine two strings into one:
The operation is called
concatenation.
>>> boo = “cone” + “cat” + “ten” + “ate”
>>> print(boo)
conecattenate
>>> foo = “one”
>>> bar = “two”
>>> full = foo + “ “ + bar
>>> print(full)
one two
If you want a string
containing N substrings, you use the * operator.
>>> foo = “foo “ * 3
>>> print(foo)
foo foo foo
*********************
********************
Quiz
PROBLEM:
1. In Python it is
possible to combine multiple strings into one.
What is the name of this
operation?
2. There is a string
value = “foobar”. You access a substring the following way:
other_value = value[1:3].
What is the name of this
operation? How long is other_value?
3. What is the index of
the first character in a string?
ANSWER:
1. Concatenation
2. Slicing. The length is
2. The last character defined by slicing operation is not
included.
3. 0
*********************
********************
Exercises
PROBLEM: There are two
strings: one = “John is strong” two = “Tea is not warm”.
Write Python code to
produce a string result = “John is not strong” out of one and two:
ANSWER:
result = one[0:8] + two[7:11] + one[8:14]
*********************
********************
Exercises
PROBLEM: Find which of
these strings doesn’t contain the letter “B”: “Foo”, “Bar”, “Zoo”,
“Loo”.
ANSWER:
>>> “B” in “Foo”
False
>>> “B” in “Bar”
True
>>> “B” in “Zoo”
False
>>> “B” in “Loo”
False
*********************
********************
Exercises
PROBLEM: Use the Python
interpreter to find the length of the string “John is strong”
ANSWER:
>>> len(“John is strong”)
14
*********************
*******
Comments
Post a Comment