String Basics

What is a String?

A string is a sequence or array of characters that have a given encoding.

Characters can be letters or digits or puctuation.

95% of the time you don't have to worry about encoding. Two notable exceptions:

  • You're dealing with code that has to work for both Python 2 and Python 3.
  • You're dealing with data that originated outside of Python, especially where foreign languages are involved.

Examples

In [1]:
# Creating string variables.
# Can use single quotes or double quotes, but they have to match
# Should try to be consistent in real code.
name = "John Lockwood"
email = 'john@codesolid.com'
zip_code = "28262"

print(zip_code)

# A Multi-line string have three single or double quotes in a row.
chief_weapon = """Our chief weapon:
Surprise
Fear
"""

print(chief_weapon)
28262
Our chief weapon:
Surprise
Fear

Strings are objects of type string.

By the way, because of this can use IDE-like features in IPython. As with other Python objects, in IPython and Jupyter notebook, can get a list of supported methods on object by typing object name a dot, and then use tab key.

In [2]:
type(email)
Out[2]:
str

Strings are immutable

All operations on strings return a new string -- they don't change the existing string (unless you re-assign the result to the variable).

In [3]:
print(name.lower())
print(name)
john lockwood
John Lockwood