Converting between lists and strings
We often need to convert between strings and lists.
Q1. Get this code working in Python:
1. monster = "Monsters are bad bad bad and we should all be very afraid."
2. print(monster)
3.
4. myMonsterList=monster.split()
5. print(myMonsterList)
Q2. Describe what the above code does.
Q3. If we do not include a parameter in the split method, then a space is used to find where to split the string. We can, however, use any character or string we like. Python will then split the string wherever it finds this character or string. It doesn't, however, include this parameter in the resulting list.
Replace line 4 with:
myMonsterList=monster.split('e') and see what happens.
Q4. Now replace line 4 again with:
myMonsterList=monster.split('ba') and see what happens.
Q5. Experiment with different strings as the parameter in split. Predict what will happen before you run each test.
Q6. We can also take a list and convert it into a string using the join method. Get the following code working:
monsterList=['witch','goblin','elf', 'evil pixie', 'ghost']
myString = ' '.join(monsterList)
print(myString)
Q7. Describe what this code is doing.
Q8. instead of a space between the single quotes, try an underscore _ character. Run the code and see what your string loks like now.
Q9. instead of an underscore between the single quotes, try a string such as fish**fingers. Run the code and see what your string loks like now.
Q10. Experiment creating a string with different characters between the words.