Working with Strings

A string is a collection of characters, in a sequence. "My name is Mark." is a string with 16 characters in it. Spaces and periods are separate characters. Strings start with single quotes or double quotes. As you have seen before you can actually do some simple “arithmetic” with strings using + and * as shown below. You can also get the length of any collection (including strings) with the len function.

(String_Manip)

    csp-16-2-1: If we wanted to add one line to the above to print “My name is MarkMarkMark”, which one of these would do it? Choose all that are correct.
  • print(start+name)
  • This just generates: My name is Mark
  • print(start+name+name+name)
  • Could you also use multiplication?
  • print(start + (3 * name))
  • This will work, but multiplication is processed before addition, so you do not have to have parentheses.
  • print(start + 3 * name)
  • This will work just fine.
    csp-16-2-2: What is the length of the string "Hi sis!"?
  • 5
  • This is just the numer of alphabetic characters. The length of a string includes the spaces and punctuation characters too.
  • 6
  • Don't forget to count the space too.
  • 7
  • The length of a string includes all the characters which includes spaces and punctuation.
  • 9
  • We don't include the single or double quotes in the length of the string.

    csp-16-2-3: What would the following code print?

    first = "Watch"
    next = 'Out'
    print ((first + next) * 2)
    
  • Watch Out
  • When you append strings together no extra spaces are added.
  • WatchOut
  • Don't forget the * 2 part. What does that do?
  • Watch Out Watch Out
  • When you append strings together no extra spaces are added.
  • WatchOutWatchOut
  • The + appends strings together and the * makes that many copies of the string appended together.
  • WatchOut2
  • The * makes that many copies of the string appended together.

Note

Remember that strings must start and end with the same character. That character can be " or ', but whatever you use as the starting character must match the ending character.

Run the code below to see what type of error you get if you use a different starting character than ending character in a string. Then try to fix the 2 errors in the code and run the code again. You should get the same results as in CodeLens 1 (String_Manip) above.

Do ‘simple arithmetic’ with the variables provided below to print ‘jellybeanjellybeanjellybean’.

Next Section - Working with Lists