String Operations
There are four binary operators that act on strings: in
, not in
, +
, and *
. The first three expect both operands to be strings. The last requires the other operator to be an integer. A one-character substring can be extracted with subscription
and a longer substring by slicing. Both use square brackets, as we’ll see below.
The in
and not in
operators test whether the first string is a substring of the second one (starting at any position). The result is True or False :
>>>
>>> 'Level1Tech' in 'Level1TechLevel1TechLevel1Tech'
True
>>> 'Level1Tech' not in 'Level1TechLevel1TechLevel1Tech'
False
>>> 'Level' in 'Level1TechLevel1TechLevel1Tech'
True
>>> '1' not in 'Level1TechLevel1TechLevel1Tech'
False
>>>
Subscription is expressed with a pair of square brackets enclosing an integer-valued expression called an index
. A subscription selects an item of a sequence (string, tuple or list) or mapping (dictionary) object. The first character is at position 0, not 1 :
>>> 'Level1Tech'[6]
'T'
>>>
The Subscription expression is related to Slicing which has been covered and continued to do so in :
The Noobs of Python: Ep.2.1 - List : Slice, Loops and Operators