Python Strings 2
Python Strings 2
STRINGS
A STRING IS A SEQUENCE OF CHARACTERS
EG: Peter
Agni
30
You can assign string to a variable by using single
quotes or double quotes
• userName = ‘Peter’
• userSpouseName = “Janet”
• userAge = ‘30’
You can assign a multiline string to a variable by
using three quotes
We can combine multiple substrings by using the
concatenate sign (+)
You can access the characters in a string one at a
time with the bracket operator.
>>> fruit = ‘foobar’
>>> letter1 = fruit[0]
>>> letter2=fruit[1]
>>>letter3=fruit[2]
>>>letter4=fruit[-1]
>>>print(letter1,letter2,letter3,letter4)
The expression in brackets is called an index. The index indicates which character in the
sequence you want.
>>>string=‘Hello world’
>>>word1=string[0:5]
>>>word2=string[6:11]
>>>print(word1)
>>>print(word2)
>>>string1=[3:]
>>>string2=[:3]
>>>string3=[3:3]
>>>string4=[:]
The length of a string
The in operator The word in is a boolean operator that takes two strings and
returns True if the first appears as a substring in the second:
(Try these in the python shell)
>>> ‘a’ in ‘banana’
>>> ‘ana’ in ‘banana’
>>> ‘seed’ in ‘banana’
String comparison
>>>‘a’ < ‘b’
>>>‘ac’ < ‘ab’
>>> ‘abc’ < ‘abd’
>>> ord(‘a’)
Built-in string functions
3. strip() method removes any whitespace from the beginning or the end
4. replace() method replaces a string with another string
5. split() method splits the string into substrings if it finds instances of the
separator
6. find() method finds the first occurrence of the specified value.