Strings
Strings
INTRODUCTION
STRING OPERATORS
• Basic Operators
◦ Arithmetic operators : + and * are the two basic operators
◦ Concatenation operator (+) :
▪ Creates a new string by joining the two operand strings
e.g. “tea” + “pot” = ‘teapot’
▪ Works with strings and strings separately for concatenation and addition respectively
and these cannot be combined
◦ Replication operator (*) :
▪ To use it with strings, a string and a number is required
e.g. “abc” * 2 = “abcabc”
▪ Works with strings and strings separately for replication and multiplication
respectively and these cannot be combined
• Membership Operators
◦ in, not in are the two operators which work for strings (and all sequence types)
▪ in – returns True if a character or substring exists in the given string, False otherwise
e.g. “a” in “heya”, “jap” in “japan” - gives True
▪ not in – returns True if a character or substring does not exist in the given string,
False otherwise
e.g. “jap” not in “Japan”, “123” not in “hello” - gives True
• Comparison Operators
◦ Python’s standard comparison / relational operators (<, >, ==, <=, >=, !=) apply to
strings also
◦ The comparison are based on standard character-by-character comparison rules for
Unicode (dictionary order)
◦ A built in function – ord ( ) takes in a single character and returns the corresponding
ordinal Unicode value
◦ The opposite of ord ( ) function is chr ( ) .
The ordinal function returns the ordinal value of a character while the latter takes the
ordinal value in integer form and returns the character corresponding to that ordinal
value.
>>> ord (‘A’)
65
>>> chr (65)
‘A’
STRING SLICING
• Many built-in functions and methods for string manipulation are offered by Python
• Every string object created in Python, is an instance of String class
• String manipulation methods can be applied using the following syntax
<stringObject>.method name ( )
• A function is independent of Class, and of association with an object and can be called
directly, while a method is class dependent and associated with a class