Importing modules
See here.
Approximate values for floats
See here.
Short-circuit evaluation
See here.
Conditional (if-else) expression
See here.
Introduction to Strings
String operators
See here.
And from class:
# String Concatenation
print("Hello" + "World" + "!") # prints HelloWorld!
print("Hello" "World" "!") # prints HelloWorld!
s = "Hello"
print(s + "World" + "!") # prints HelloWorld!
print(s "World" "!") # Error
print("hi"*3) # prints hihihi
print(3*"hi") # prints hihihi
print(2*"hi"*2) # prints hihihihi
# String Indexing
s = "Go Tartans!"
print(s[0]) # prints G
print(s[5], s[10], s[3]) # prints r ! T
print(s[-1]) # prints !
print(len(s)) # prints 11
print("Yabadabaduuu!"[5]) # prints a
print(s[len(s)]) # Crashes: index error
# String Slicing
print(s[3:len(s)]) # prints Tartans!
print(s[0:len(s)]) # prints Go Tartans!
print(s[3:]) # prints Tartans!
print(s[:1]) # prints G
print(s[:]) # prints Go Tartans!
print(s[0:len(s):2]) # prints G atn!
print(s[::]) # prints Go Tartans!
print(s[len(s)-1:0:-1]) # prints !snatraT o
print(s[len(s)-1:-1:-1]) # prints nothing (range is empty)
print(s[::-1]) # prints !snatraT oG
# Strings are immutable
s[3] = "t" # error
s += " haha" # creates a new string in memory
print(s) # prints Go Tartans! haha
s = s[:3] + "t" + s[4:] # effectively s[3] = "t"
print(s) # prints Go tartans! haha
Looping over strings
See here. Skip sections 3 and 4.
# Looping over a string with an index:
s = "hello"
for i in range(len(s)):
print(i, s[i])
# Looping over a string without an index:
for c in s:
print(c)
Example: isPalindrome
See here. Recommended implementation:
def isPalindrome(s):
mid = len(s)//2
for i in range(mid):
if (s[i] != s[len(s)-1-i]): return False
return True
String related built-in functions
See here.