Working with Python Strings

Background Info

html

Python Strings: are a sequence data type that are immutable.

  • Operators and functions applied to strings returns a new string derived from the original.
  • Strings can be delimited by single (' '), double (" "), and triple (''' ''') quotations: Strings can contain tab (\t) and newline (\n) characters.
  • Operators: in, +, *
  • Built-in functions: len, max, min
  • String elements can be indexed and sliced like list sequences, but these methods cannot be used to add, remove, or replacement elements.

Why is this important?
Strings are an important datatype and knowing how to create, index, and return new versions of strings is a critical skill.

html

Creating Strings

Create a string using str() constructor:
str()
Create a string with variable assignment:
variable = "string"


Concatenate and Combine Strings


Combine using "+":
string + string
Combine using " ":
string + "string"


Operators and Common Built-in Functions

Operator Functions:
element in set
Return number of elements in a set:
len(set)


Changing Case Functions

Title case.
string.title(): Upper Case
string.upper():
Lower Case
string.upper():


Indexing Strings


Returns the first index that matches character(s)
string.index('character(s)')


Replace Function

string.replace(old, new, count)


Dealing with Whitespace

Strip white space on right side: string.rstrip()
Strip white space on left side: string.lstrip()
Strip white space on both side: string.strip()