Python Strings



Types of string



You can use any of the following to open and close a string:
• Single Quotes ' '
• Double Quotes " "
• Triple Single Quotes ''' '''
• Triple Double Quotes """ """
◇ A triple-quoted string (""") at the beginning of a Python file, function, or class are called docstrings


# Types of string
single_quoted = 'morgan everett'
double_quoted = "JC Denton"     # can't put quotes within double quotes

multi_line = """
In the beginning, the NSF was a nuisance.

Now, they are a catastrophe.

"""


Create String with Quotation Marks



# No need to use escape characters
signle_quoted_with_quotes = 'morgan "Hi" everett'

# Output
'morgan "Hi" everett'


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Escape Characters



# Escaping characters
apostrophes = 'You\'ll never need to escape from UNATCO HQ...'
newline = 'Youll \never need to escape from UNATCO HQ...'
tab = 'Youll never need \to escape from UNATCO HQ...'
forward_slash = 'Youll never need to escape \\from UNATCO HQ...'
quotes = 'Youll never need to escape from "UNATCO HQ"...'


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Common String Methods



# Common string methods
double_quoted.upper()       # upper case
# or
"JC Denton".upper()

double_quoted.lower()       # lower case
double_quoted.title()       # title case


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

String Concatenation



# Build some strings with concatenation
print(single_quoted + " has an agenda all his own.")
whitespace_str = "\nOr does he?\t\the does..."
biggest_string_ever = single quoted + whitespace_str

# Print it all out!
print(biggest_string_ever)

exit(0)


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

String Arithmetic Hijinks



# String Arithmetic Hijinks
"three" * 5

# Output
threethreethreethreethree


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

More String Methods



"{}".format(): The .format() method lets you insert named or unnamed placeholders {} in a string and then use the .format() method to insert values into those placeholders
"".split(): The .split() method lets you split a string into multiple strings using a separator that you provide as the delimiter
"".join(): The .join() method lets you put a sequence of strings together using, joining them with a separator that you provide

# format()
>>> "Hi, my name is {}!".format("Chris")
'Hi, my name is Chris!'

>>> "Hi, my name is {name}, and I am a {what}!".format(name="Bob", what="coder")
'Hi, my name is Bob, and I am a coder!'

# split()
>>> "a b c".split(" ")
['a''b''c']

# join()
>>> ",".join(['a''b''c'])
'a,b,c'

Index