Detail This method receives a number and returns the integral form of that number.
So If we pass 1.5 to int(), it will return 1. It always removes the fractional part of the number.
floating = 1.23456# Convert to int and print.
Int, string. A number is converted into a string with str. And a string is converted into a number with int. In this example, we do these two conversions.
And We show the value types by using them. We use len() on the string and add one to the number.
So The string "123" has three characters. And the number 123 is increased to 124 when we add one to it.
# Convert number to string.
number = 123
value = str(number)
# Print the string and its character count.
# Convert string to number.
number2 = int(value)
# Print the number and add one.
print(number2 + 1)123
Class, string. We can specify how a class is converted to a string with the __repr__ method. This method returns a string. We can have it return values of fields in the class.
Note The repr and str methods (with no underscores) are used on instances of a class. If the __repr__ method is defined, it will be used.
Tip Classes like list also have repr (representation) methods. This is why you can directly print a list.
self.size = 1
self.name = "Python"
# Return a string.
return "Size = " + str(self.size) + ", Name = " + str(self.name)
t = Test()
# Str and repr will both call into __repr__.
s = str(t)
r = repr(t)
# Display results.
print(r)Size = 1, Name = Python
Size = 1, Name = Python
String, chars. We can get the chars from a string with a list comprehension. This syntax uses an inner loop expression to loop over each char in the string. This results in a list of chars.
value = "cat"# Get chars from string with list comprehension.
list = [c for c in value]
print(list)['c', 'a', 't']
Bytes, string. Python 3 has the space-efficient bytes type. We can take a string and convert it into bytes with a built-in. We provide the "ascii" encoding as a string argument.
Detail To convert from the bytes data back into a string, we can use the decode method. We again must provide an encoding string.
# Convert from string to bytes.
value = "carrot"
data = bytes(value, "ascii")
# Convert bytes into string with decode.
original = data.decode("ascii")
Bytes, megabytes. A number in one unit, like bytes, can be converted into another, like megabytes. Here we divide by 1024 twice. Further conversions (bytes, gigabytes) are possible.
Note Large files have many bytes. In an interface, displaying this number is awkward and hard to read.
Detail One megabyte contains 1024 kilobytes. And 1 kilobyte contains 1024 bytes.
So To get from bytes to megabytes, we divide by 1024, and then by 1024 again: two divisions are needed.
And To go from kilobytes to megabytes, we need just one division by 1024. This is simple, but testing is important.