Go to: Na-Rae Han's home page  

Python 3 Notes

        [ HOME | LING 1330/2330 ]

Tutorial 4: Introduction to Strings

<< Previous Tutorial           Next Tutorial >>
On this page: Strings in '' or ""; using + (concatenation operator) and * (multi-copy concatenation operator) on strings.

Video Tutorial


Python 3 Changes

NONE!

Video Summary

  • A series of characters designated as one object is known as a string. As seen in previous tutorials, both strings and numbers can be given as values for variables. To designate a string in Python, surround a desired series of characters with either single quotes (' ') or double quotes (" "). Ex: 'five' or "the romans" are both strings in Python.
  • Any combination of letters, numbers, spaces, and/or special characters can be designated as a string, so a full sentence with spaces between words that ends in a question mark is a valid string in Python if surrounded in single or double quotes. Ex: 'Did you go to the store?'
  • Further single quotes, apostrophes, and double quotes are allowed within a string, however, the string must end in the same type of quote with which it was started. Ex: "Why my teeth are all a-hurtin' for now?" is a valid string but "Why my teeth are all a hurtin' for now?' is not a valid string and will produce an error.
  • Interestingly, you can use mathematical operators such as "+" and "*" on strings: the former is a concatenation operator, and the latter works as a "multi-copy concatenation operator".

Learn More

  • Are you using the command-line history shortcuts (Win: Alt + p/n, Mac: Ctrl + p/n)? You should. Soon the Python commands will start getting longer, and if you mistype a command it is much easier to bring up the old command and edit it than retype the entire thing.
  • Operators such as "+" and "*" work on multiple data types including integers, floats and strings. Depending on the argument data type, they do different things. For example, "+" in 6 + 6 is a addition operator, but "+" in 'boy' + 'friend' is a concatenation operator and yields 'boyfriend' as the return value. These operators are called "overloaded" operators: you will need to pay close attention to the data type of the arguments you supply.
  • More on strings coming up in Tutorial 6.
  • Since we are linguists, we will be working heavily with strings. There are tons of handy operations ("methods") defined on strings. The first part is available here: String Methods Part 1, and the second part: String Methods Part 2.
  • Once you get comfortable with lists, you should also check out Splitting and Joining Strings.

Explore