Data Types:

  • In the real world, we use data all the time without bothering to consider what kind of data we’re using. For example, consider this sentence:
    • ā€œIn 2007, Harpua paid $120,000 for his house at 87 Cullowhee Mountain Drive.ā€ This sentence includes at least four pieces of data – a name, a date, a price and an address – but of course you don’t have to stop to think about that before you utter the sentence.
      • We don’t have to consider that:
        • The name consists of only text characters.
        • The date and price are numbers and so on.
      • When we use data in a program, we do need to keep in mind the type of data we’re using.

What is a String?

  • A string is simply a series of characters.
  • In Python, a string is a series of characters enclosed in single or double quotation marks. This allows for flexibility between quotes and apostrophes.
python
1"This is a string."
2
3'This is also a string.'

Changing Case in a String with Methods:

  • One task to do with a string is to change the case of the words. Note the following input:
python
1name = "jean-luc picard"
2print(name.title())

Running this would provide the following output:

1Jean-Luc Picard
  • In this example, the lowercase string ā€œjean-luc picardā€ is stored in the variable name. The method title() appears after the variable in the print() statement.
    • A method is an action that Python can perform on a piece of data.
    • The dot (.) after name in name.title() tells Python to make the title() method act on the variable name.
    • Every method is followed by a set of parentheses, because methods often need information to do their work.

Concatenating Strings (aka Combining Strings):

  • We can join two or more strings to form a new string using the concatenation operator +
  • In other words, Python uses the plus symbol (+) to combine strings.
  • In the below example, we use + to list the author’s name following the author’s quote which appears on the second line.
python
1author = "albert einstein"
2quote = "\nA person who never made a mistake never tried anything new."
3
4print(author + quote)

Running this would provide the following output:

1albert einstein
2A person who never made a mistake never tried anything new.
  • Note the whitespace syntax (\n) adds a new line in the string.
    • Whitespace refers to any nonprinting character, such as spaces, tabs, and end-of-line symbols.