NB: Strings

Kinds of quotes

Strings are signified by quotes.

Single and double quotes are identical in function.

They must be “straight quotes” though – cutting and pasting from a Word document with smart quotes won’t work.

'hello world!' == "hello world!"

Quote prefixes

r strings

Prefixing a string causes escape characters to be uninterpreted.

print("Sentence one.\nSentence two.")
print(r"Sentence one.\nSentence two.")

f strings

Prefixing a string with f allows variable interpolation – inplace evaluation of variables in strings.

ppl = 'knights'
greeting = 'Ni'
print(f'We are the {ppl} who say {greeting}!') # Output: We are the knights who say Ni!

The brackets and characters within them (called format fields) are replaced with the passed objects.

print(b"This is a sentence.")
print("This is a sentence.")

Printing print()

Python uses a print function.

print("This is a simple print statement")

Python supports special “escape characters” in strings that produce effects when printed.

\\     Backslash (\)
\'     Single quote (')
\"     Double quote (")
\n     ASCII Linefeed, aka new line

Note that these are not unique to Python. They are part of almost all languages.

# Tab character ( \t )
print("Hello,\tWorld! (With a tab character)")
Hello,  World! (With a tab character)
# Inserting a new line (line feed) character ( \n )
print("Line one\nLine two, with newline character")
Line one
Line two, with newline character
# Concatenation in strings: 
# Use plus sign ( + ) to concatenate the parts of the string
print("Concatenation," + "\t" + "in strings with tab in middle")
# If you wanted to print special characters
# Printing quotes
print('Printing "quotes" within a string') # mixing single and double quotes
# What if you needed to print special characters like (\) or (') or (")
print('If I want to print \'single quotes\' in a string, use backslash!')
print("If I want to print \"double quotes\" in a string, use backslash!")
print('If I want to print \\the backslash\\ in a string, also use backslash!')
If I want to print 'single quotes' in a string, use backslash!
If I want to print "double quotes" in a string, use backslash!
If I want to print \the backslash\ in a string, also use backslash!

The print function puts spaces between strings and a newline at the end, but you can change that:

print("This", "is", "a", "sentence")
print("This", "is", "a", "sentence", sep="--")
print("This", "is", "a", "sentence")
print("This", "is", "a", "sentence")
print("This", "is", "a", "sentence", end=" | ")
print("This", "is", "a", "sentence")

Comments

Comments are lines of code that aren’t read by the interpreter.

They are used to explain blocks of code, or to remove code from execution when debugging.

# This is single-line comment

These following are multiline strings that can serve as comments:

foo = '''
This is an
example of
a multi-line
comment: single quotes
'''
foo
'\nThis is an\nexample of\na multi-line\ncomment: single quotes\n'
print(foo)

This is an
example of
a multi-line
comment: single quotes
"""
Here is another
example of
a multi-line
comment: double quotes
"""

Note that multiline comments also evaluate as values.

Run-time User Input

answer = input("What is your name? ")
print("Hello, " + answer + "!")

Some String Functions

Built-in string methods and functions.

See [Common String Operations](https://docs.python.org/3/library/string.html) for more info.

.lower(), .upper()

'BOB'.lower() #.upper()
'bob'

.split()

Parase a string based on a delimiter, which defaults to whitespace.

NOTE: This does not use regular expressions.

This returns a list.

montyPythonQuote = 'are.you.suggesting.coconuts.migrate'
'are.you.suggesting.coconuts.migrate'.split('.')
['are', 'you', 'suggesting', 'coconuts', 'migrate']
montyPythonQuote
'are.you.suggesting.coconuts.migrate'
montyPythonQuote.split('.') # split by the '.' delimiter. Result: a list!
['are', 'you', 'suggesting', 'coconuts', 'migrate']

.strip(), .rstrip(), lstrip() Strip methods

Strip out extra whitespace using strip(), rstrip() and lstrip() functions

.strip() removes white space from anywhere
.rstrip() only removes white space from the right-hand-side of the string
.lstrip() only removes white space from the left-hand-side of the string

str1 = '  hello, world!'    # white space at the beginning
str2 = '  hello, world!  '  # white space at both ends
str3 = 'hello, world!  '    # white space at the end
str1, str2, str3
str1.lstrip(), str1.rstrip()
str2.strip(), str2.rstrip()
str2.lstrip(), str3.rstrip()
status.startswith('a')
status.endswith('s')

.replace()

"latina".replace("a", "x")

.format()

Variable values can be embedding in strings using the format() function.
Place {} in the string in order from left to right. followed by .format(var1, var2, ...)`

epoch = 20
loss = 1.55

print('Epoch: {}, loss: {}'.format(epoch, loss))

This breaks, as three variables are required based on number of {}

print('Epoch: {}, loop: {}, loss: {}'.format(epoch, loss))

.zfill()

Basic usage of the str.zfill() method (pads a numeric string on the left with zeros) It understands about plus and minus signs

print('12'.zfill(5))       # Output: 00012
print('-3.14'.zfill(7))    # Output: -003.14
print('3.141592'.zfill(5)) # Output: 3.141592

Strings are Lists

Actually, they are list-like.

Here are some functions applicable to strings because they are lists.

len() Length

This is built-in length funciton tells us how many characters in the string.

It also applys to any list-like object, including strings, lists, dicts, sets, and dataframes.

len?
my_new_tring = 'This is a string'
len(my_new_tring)

Indexing

Since strings are sequences in Python, each character of the string has a unique position that can be indexed.

Indexes are indicated by suffixed brackets, e.g. foo[]

my_new_tring[0] # displays the first character of the string
            # first position is position zero. Will display 'h'
my_new_tring[-1] # displays the last character. Negatives count backwords.

Slicing

We can used the colon to ‘slice’ strings (and lists)

my_new_tring[0:4] # First four characters (index positions 0-3)
my_new_tring[:4]  # Beginning (0) to (n-1) position
my_new_tring[4:]  # Fifth character and onwards until the end of the string

it is NOT possible to reassign elements of a string. Python strings are immutable.

status = 'success'
status[0] = 't'

Add strings and handle pathing