String type
str

A string holds a sequence of characters, which includes whitespace characters (e.g., spaces) as well as punctuation. A string literal is surrounded by single quotes '' or double quotes "". Be careful not to use ‘fancy’ single quotes or “fancy” double quotes (also known as “smart quotes”)! That might happen if you copy-and-paste an example from a pdf document, for example. It won’t work – again, computers are not that smart!

  • Example string literals: "Hello", "hello, there", "Hi!"

Note:

  • The backslash \ character is a special character in Python. To have it appear in a string, you must escape it with itself. For example, if you want your text to say “This is a backslash \” you must enter This is a backslash \\.

  • The newline character is denoted \n and can be quite handy! It is used to create a new line, like the enter/return button on your keyboard.

string operators

There are two string operators that look like arithmetic operators: the + (concatenation) operator and the * (repetition) operator.

Converting between strings and integers

Notice how both integers and strings have + and * operators. Python determines whether to perform addition or string concatenation based on the types of the operands (the data being manipulated by +). So, what happens if we use + when the operands are strings of digits? Compare the results of these two expressions.

value1 = 100 + 12

value2 = '100' + '12'

value3 = '100' + 12


value1 will be assigned 112, while value2 will be assigned ‘10012’. Attempting to execute the third statement will result in a “type error”, since one operand is a string while the other is an int.

Sometimes, we may have a string that contains only digits and want to treat it as a number. Python can convert the string to an int as follows:

strValue = '100'

intValue = int( strValue )


Similarly, if we have an integer and want to treat it as a string, Python can convert it for us as follows:

intValue = 100

strValue = str( intValue )


At this point, you might wonder why you would ever want to do this. You will see an example of that in next week's lab and homework.