Block B

Python String Methods


>>> alpha = "abcdefghij"
>>> 5 = x
  File "<stdin>", line 1
SyntaxError: cannot assign to literal
>>> # lvalue:  assignable memory
>>> alpha.upper()
'ABCDEFGHIJ'
>>> alpha
'abcdefghij'
>>> alpha.capitalize()
'Abcdefghij'
>>> alpha.center(25)
'        abcdefghij       '
>>> alpha.center(25,"*")
'********abcdefghij*******'
>>> magic = "abracadaver"
>>> magic.count("a")
4
>>> magic.count("a", 5)
2
>>> magic.count("a", 5,7)
1
>>> magic.endswith("r")
True
>>> magic.endswith("er")
True
>>> magic.endswith("ver")
True
>>> magic.startswith("ba")
False
>>> magic.startswith("ab")
True
>>> magic.startswith("abracadaver")
True
>>> magic.find("c")
4
>>> magic.rfind("a")
7
>>> magic.replace("a", "A")
'AbrAcAdAver'
>>> magic.isalnum()
True
>>> magic += "456"
>>> magic
'abracadaver456'
>>> magic.isalnum()
True
>>> magic += ";;;@#%#$!@"
>>> magic.isalnum()
False
>>> s = "2bornot2b"
>>> s.isidentifier()
False

Rule for Variable Names Variable names start with an alpha charcter or an _. Subequent characters are alphanumeric or underscores.

In Python we tend to use snake notation.


>>> number_of_eyes - 47
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'number_of_eyes' is not defined
>>> number_of_eyes = 47

In Java, camel notation predominates.


int numberOfEyes = 48;

>>> cadet = "   \t\t\n\n   "
>>> cadet.isspace()
True
>>> print(cadet)
   		

   
>>> cadet
'   \t\t\n\n   '
>>> poker = "      strip now    "
>>> poker.strip()
'strip now'
>>> poker.lstrip()
'strip now    '
>>> poker.rstrip()
'      strip now'
Built-in Functions


>>> ord("a")
97
>>> ord("b")
98
>>> ord("c")
99
>>> ord("d")
100
>>> bin(ord("d"))
'0b1100100'
>>> ord("&")
38
>>> bin(ord("&"))
'0b100110'
>>> chr(97)
'a'
>>> chr(99)
'c'
>>> chr(98)
'b'
>>> chr(945)
'α'
>>>