Strings operations¶
Definition¶
A string is a list of characters. We often want to make changes to strings - this is called string manipulation. The most important string manipulation is the ability to join two strings together - this is known as concatenation.
Note
A strings is a list of characters, so we can manipulate them just like lists.
Easy example¶
a = 'good '
b = 'morning'
greeting = a + b
print(greeting)
good morning
greeting
now stores 'good morning'
Note
Notice how a space character needs to also be stored in the variable a
.
Syntax - concatenation¶
string1 + string2
Examples¶
Example 1 - String assignment¶
name = input('What is your name? ')
print(name)
What is your name? Sam
Sam
Example 2 - String concatenation¶
subject = 'Mrs Smith'
verb = 'runs'
object = 'home'
sentence = subject + verb + object
print(sentence)
sentenceWithSpaces = subject + ' ' + verb + ' ' + object
print(sentenceWithSpaces)
Mrs Smithrunshome
Mrs Smith runs home
Note
Notice how the variable sentence
doesn’t have any spaces between each string that was concatenated, but sentenceWithSpaces
does.
Example 3 - Length of a string¶
lengthOfSentence = len('This is a sentence')
print(lengthOfSentence)
18
Note
The length of a string will count every character inside it, including spaces.
Example 4 - Output strings and numbers¶
age = 15
name = 'Amy'
height = 159.3
print('Hi ' + name + ', you are age ' + str(age) + ' and ' + str(height) + ' cm tall.')
Hi Amy, you are age 15 and 159.3 cm tall.
Example 5 - Get the character at the nth position in the string¶
sentence = 'my Python program'
a = sentence[0]
b = sentence[5]
print(a)
print(b)
m
t
Note
The characters in a string are numbered starting at 0 (zero).
Example 6 - Looping through a string (method 1)¶
name = 'hello'
for letter in name:
print(letter)
h
e
l
l
o
Note
You would normally do something more useful with letter
than just print it.
Example 7 - Looping through a string (method 2)¶
name = 'hello'
for i in range(len(name)):
print('Character number ' + str(i) + ' is: ' + name[i])
Character number 0 is: h
Character number 1 is: e
Character number 2 is: l
Character number 3 is: l
Character number 4 is: o
Example 8 - Strip (remove whitespace characters)¶
sentence = ' This is some text. '
sentenceStripped = sentence.strip()
print(sentence)
print(sentenceStripped)
This is some text.
This is some text.
Note
Notice how the whitespace to the left and right of the string has been removed.
Example 9 - Split (split a string into smaller strings)¶
gameDetails = 'pacman,1980,Japan,Namco'
listOfDetails = gameDetails.split(',')
gameName = listOfDetails[0]
year = listOfDetails[1]
country = listOfDetails[2]
company = listOfDetails[3]
print(listOfDetails)
print(gameName + ' was created in ' + year + ' and made in ' + country + ' by ' + company)
['pacman', '1980', 'Japan', 'Namco']
pacman was created in 1980 and made in Japan by Namco
Note
When you split a string, the result will be a list of each of the items found before the split character (in this case a comma).
Example 10 - Lower (to convert characters to lower case)¶
name = 'Jacob SMITH'
nameInLowercase = name.lower()
print(nameInLowercase)
jacob smith
Example 11 - Upper (testing an input)¶
name = 'sMith'
if name.upper() == 'SMITH':
print('Your name is SMITH')
You're name is SMITH
Note
Converting an input or variable to upper case or lower case will make it easier for comparisons in IF statements.
Example 12 - Isnumeric (find if a string contains digits only)¶
a = 'hello456'
b = '456'
c = '456.23'
d = '-23'
print(a.isdigit())
print(b.isdigit())
print(c.isdigit())
print(d.isdigit())
False
True
False
False
Note
isdigit()
is checking if every character in the string is a number. Negative or floating point numbers will therefore not be True as they contain a -
character or .
character.
Example 13 - Find left characters of a string (slice)¶
phrase = 'hello everyone'
print(phrase[:7]) #Find first seven characters
hello e
Example 14 - Find right characters of a string (slice)¶
phrase = 'hello everyone'
print(phrase[7:]) #Find last seven characters
veryone
Example 15 - Find substring between two points (slice)¶
phrase = 'hello everyone'
print(phrase[2:8])
llo ev
Note
Returns the characters between 2
and 8
, but doesn’t include the 8th character.
Key points¶
Note
The first letter of a string is in position 0
. This is the same as any list which starts at 0
.