Strings

Strings

A string is a piece of text. Strings are written between double quotes or single quotes — the two forms are identical:

name = "Parsnip"
language = 'Python'

The + operator joins strings. This is called concatenation:

first = "Par"
last = "Snip"
full = first + last
print(full)

Output:

ParSnip

Concatenation adds nothing between the strings. To get a space, include one:

full = first + " " + last
print(full)

Output:

Par Snip

+ only joins strings with strings. Joining a string and a number is an error:

print("Age: " + 36)

Output:

TypeError: can only concatenate str (not "int") to str

A later lesson covers converting between the two.

Exercise

  1. Create street holding "Bourke St".
  2. Create number holding the string "1" — in quotes.
  3. Create address by concatenating number, a space, and street. The result is "1 Bourke St".
  4. Print address.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestStrings(unittest.TestCase):
    def test_street(self):
        self.assertEqual(street, "Bourke St")

    def test_number(self):
        self.assertEqual(number, "1")

    def test_address_joins_street_and_number_with_a_space(self):
        self.assertEqual(address, "1 Bourke St")
street = "Bourke St"
number = "1"
address = number + " " + street

print(address)
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.