PYTHON
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
len is a built-in function that returns the number of characters in a string
>>> fruit = 'banana’
>>> len(fruit)
6
Strings are immutable, which means you can’t change an existing string.
Eg: >>> string = ‘Hello world!’
>>> string[0] = ‘J’
TypeError: 'str' object does not support item assignment
The best we can do is to create a new string by manipulating the existing
string. >>> string = 'Hello world!’
>>> new_string = ‘J’ + string[1:]
>>> print(new_string)
>>> Jello, world!
Strings with while loop
>>>String=‘My name is Peter’
>>>index=0
>>>while index <= len(string):
letter = string[index]
print (letter)
index = index + 1
The in operator
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
1. upper() method returns the string in upper case.
2. lower() method returns the string in lower case
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.
7. count() method returns the number of occurrences of a substring in the given
string.
Formatting Strings using the format() method
1. Use the format() method to insert numbers into strings.
2. The format() method takes unlimited number of arguments, and are placed
into the respective placeholders.