HomeSearch

Python Convert Types

Perform conversions on objects. Convert tuples, strings, lists and dictionaries.

Convert.

In its early life the butterfly has no wings. As time passes it grows. Its beautiful wings emerge from this conversion. Its shape changes.

For a butterfly,

only one conversion can be done. But Python types can be converted in many ways. Often we employ built-in methods like str() or int or float.

Tuple, list.

This program creates a tuple with 3 elements. It then converts that tuple into a list with the list() method. This call returns a list.

Result: The program shows that the 2 collections are separate. They occupy different locations in memory.

List: The list built-in method copied all the tuple's elements into a separate, new collection.

Python program that converts tuple to list vegetables = ("carrot", "squash", "onion") # Convert to list. veg2 = list(vegetables) veg2.append("lettuce") # Print results. print(vegetables) print(veg2) Output ('carrot', 'squash', 'onion') ['carrot', 'squash', 'onion', 'lettuce']

Tuple, string.

A tuple can be converted into a single string. This is best done with the string join method. Join() is called on a delimiter string.

Tip: We pass Join() a tuple, and the result is a string containing the tuple's items.

Python program that converts tuple, string tup = ("rabbit", "mouse", "gorilla", "giraffe") # Join tuple with no space. s = "".join(tup) print(s) # Join tuple with slash. s = "/".join(tup) print(s) Output rabbitmousegorillagiraffe rabbit/mouse/gorilla/giraffe

List, string.

Lists can also be converted into strings with the join method. This code sample is the same as one that converts a tuple, but it uses a list.

Separators: We join() together the strings with no separator, and with a semicolon.

Tip: Join can handle any iterable collection, not just tuples and lists. Try it with a set.

Python program that converts list, string vehicles = ["car", "truck", "tractor"] # Convert list to string with join. result = "".join(vehicles) # Convert with semicolons separating strings. result2 = ";".join(vehicles) print(result) print(result2) Output cartrucktractor car;truck;tractor

Dictionary, list.

With the list() method, we can also convert a dictionary to a list. There is some complexity here. When we call items() on a dictionary, we get a view.

And: A view is different from a list. It cannot be manipulated in the same ways.

Items: We get a view of the dictionary with items() and then convert that to a list. So we actually convert the dictionary to a list.

Tip: With dictionary views, we can change the order. For example, we can use the sorted() method to reorder elements in a view.

Python program that converts dictionary vegetables = {"carrot": 1, "squash": 2, "onion": 4} # Convert dictionary to list of tuples. items = list(vegetables.items()) for item in items: print(len(item), item) Output 2 ('carrot', 1) 2 ('squash', 2) 2 ('onion', 4)

Int built-in.

Numbers can be converted to different types. In many languages this is called explicit casting. In Python we use a method syntax, such as int(), to do this.Int

Int: 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.

Python program that converts to int floating = 1.23456 # Convert to int and print. print(floating) print(int(floating)) Output 1.23456 1

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.

Python program that converts int, string # Convert number to string. number = 123 value = str(number) # Print the string and its character count. print(value) print(len(value)) # Convert string to number. number2 = int(value) # Print the number and add one. print(number2) print(number2 + 1) Output 123 3 123 124

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.

Python program that converts class to string class Test: def __init__(self): self.size = 1 self.name = "Python" def __repr__(self): # 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(s) print(r) Output 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.
Python program that gets list of chars value = "cat" # Get chars from string with list comprehension. list = [c for c in value] print(list) Output ['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.

Decode: To convert from the bytes data back into a string, we can use the decode method. We again must provide an encoding string.

Python program that converts bytes, string # Convert from string to bytes. value = "carrot" data = bytes(value, "ascii") print(data) # Convert bytes into string with decode. original = data.decode("ascii") print(original) Output b'carrot' carrot

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.

Convert: 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.

Python program that converts bytes, megabytes def bytestomegabytes(bytes): return (bytes / 1024) / 1024 def kilobytestomegabytes(kilobytes): return kilobytes / 1024 # Convert 100000 bytes to megabytes. megabytes1 = bytestomegabytes(100000) print(100000, "bytes =", megabytes1, "megabytes") # 1024 kilobytes to megabytes. megabytes2 = kilobytestomegabytes(1024) print(1024, "kilobytes =", megabytes2, "megabytes") Output 100000 bytes = 0.095367431640625 megabytes 1024 kilobytes = 1.0 megabytes

Dict.

With the dictionary built-in, we can convert from a list of tuples (with keys, values) to a dictionary. Dict() is a useful built-in method.dict

A conversion note.

If your conversion requires processing, consider a custom method. In programming, conversions are often necessary. Reducing conversions usually improves performance.

A summary.

Conversions in Python use many syntax forms. Some conversions are numeric. These can be done with mathematical methods or arithmetic.

Often,

conversions are encapsulated in a method definition. And for compound types such as collections, the Python language provides many built-in methods to convert, such as list().
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.