'hello world!' == "hello world!"
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.
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.
= 'knights'
ppl = 'Ni' greeting
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")
Run-time User Input
= input("What is your name? ")
answer print("Hello, " + answer + "!")
Some String Functions
-in string methods and functions.
Built
//docs.python.org/3/library/string.html) for more info. See [Common String Operations](https:
.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.
= 'are.you.suggesting.coconuts.migrate' montyPythonQuote
'are.you.suggesting.coconuts.migrate'.split('.')
['are', 'you', 'suggesting', 'coconuts', 'migrate']
montyPythonQuote
'are.you.suggesting.coconuts.migrate'
'.') # split by the '.' delimiter. Result: a list! montyPythonQuote.split(
['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
= ' hello, world!' # white space at the beginning
str1 = ' hello, world! ' # white space at both ends
str2 = 'hello, world! ' # white space at the end str3
str1, str2, str3
str1.lstrip(), str1.rstrip()
str2.strip(), str2.rstrip()
str2.lstrip(), str3.rstrip()
'a') status.startswith(
's') status.endswith(
.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, ...
)`
= 20
epoch = 1.55
loss
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?
= 'This is a string' my_new_tring
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[]
0] # displays the first character of the string
my_new_tring[# first position is position zero. Will display 'h'
-1] # displays the last character. Negatives count backwords. my_new_tring[
Slicing
We can used the colon to ‘slice’ strings (and lists)
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 my_new_tring[
it is NOT possible to reassign elements of a string. Python strings are immutable.
= 'success'
status 0] = 't' status[
Add strings and handle pathing
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.
These following are multiline strings that can serve as comments:
Note that multiline comments also evaluate as values.