Playing with Strings (String manipulation)
Strings are a collection of characters, such as text or abc123. The fact they are a collection means they can be manipulated in different ways
Printing
We have seen you can print using the print ("hello") method. We can also assign a string to a variable then print thae variable:
- a = "hello"
- print(a)
Both methods achieve the same print out.
We can also use the + and * arithmetic commands with strings - try these out in the trinket below
- print ("hello" *2) will print the string twice - as would print (a*2)
- print ("cat"+"dog") will join the two strings together - this is called concatenation
Slicing
Slicing slices the string into sections. As the string is a collection each character can be referred to. Strings (and lists) count from 0. Take the string "bricks".
Its length is 6 (There are 6 letters) but the b is in postion 0 and the s in position 5
b | r | i | c | k | s | |
position | 0 | 1 | 2 | 3 | 4 | 5 |
You can print individual letters or a group of them
- word = "bricks"
- print (word[1]) would print the r
- print (word[0:2]) would print the b and the r (it stops one position before)
- print word[:2]) would also print br. It goes from start to the number given (or one before)
- print (word[2:6]) would print icks
- print(word[2:]) prints icks too - it goes from 2 to the end)