Block F

Casting Examples


>>> int("234")
234
>>> str(234)
'234'
>>> bool(3)
True
>>> bool(6)
True
>>> bool(0)
False
>>> bool(-6)
True
>>> bool(0.0)
False
>>> float(5)
5.0
>>> float(2**10000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: int too large to convert to float
>>> int(4.5)
4
>>> int(-4.5)
-4
>>> int(1e100)
10000000000000000159028911097599180468360808563945281389781327557747838772170381060813469985856815104
>>> int(1.2342332e100)
12342332000000000720094562463352703468167593571020121408730236554716854360539113449158086194481856512

Base 7 fun


>>> int("345", 7)
180
>>> int("346", 7)
181
>>> int("350", 7)
182

A cheap conversion mechanism.


>>> 0xabc
2748
>>> 0o123
83

I'm gonna put a hex on you...


>>> hex(100)
'0x64'
>>> oct(100)
'0o144'
>>> bin(100)
'0b1100100'

Format Strings


>>> x = 3
>>> y = 7
>>> print(f"{x}*{y} = {x*y}")
3*7 = 21

Better than this.


>>> print(str(x) + "*" + str(y) + " = " + str(x*y))
3*7 = 21

Special Characters Note the escape sequences for newline and tab.


>>> print("1\n2\t3\n4\t5\t6")
1
2	3
4	5	6

>>> print("\u03b1")
α
>>> print("\u03b2")
β
>>> print("\u03b3")
γ
>>> print("\u03b4")
δ
>>> print("\u5525")
唥
>>> print(r"\u5525")
\u5525

Raw Strings Precede these with an r and a whack is just a whack.


>>> print(x)
C:\Bill Gates\sux\Microsoft\poop
udnik
>>> x = r"C:\Bill Gates\sux\Microsoft\poop\nudnik"
>>> print(x)
C:\Bill Gates\sux\Microsoft\poop\nudnik

Triple-Quoted Strings


>>> quack = """I want
... duck for dinner"""
>>> print(quack)
I want
duck for dinner

A triple-quoted string can be a format string.


>>> print(f"""{x} sucks
... and I don't like it""")
C:\Bill Gates\sux\Microsoft\poop\nudnik sucks
and I don't like it

You can use single quotes for triple-quoted strings, too.


>>> print(''' foo
... goo
... hoo
... boo 
... boo''')
 foo
goo
hoo
boo 
boo

String Methods

Let's capitalize.


>>> x = "cowabunga"
>>> x.capitalize()
'Cowabunga'

Note the original string unchanged; you are handed a new one. Save it to a variable if you need it later.


>>> y = x.capitalize()
>>> y
'Cowabunga'

Make us!

*
**
***
****
*****
    *
   ***
  *****
 *******
*********
     *
    * *
   * * *
  * * * *
 * * * * *
* * * * * *
    * *
    * *

Using input