Академический Документы
Профессиональный Документы
Культура Документы
Python 3
Posted October 20, 2016 613views Python Development
Introduction
In Python, data types are used to classify one particular type of data, determining the
values that you can assign to the type and the operations you can perform on it. When
programming, there are times we need to convert values between types in order to
manipulate values in a different way. For example, we may need to concatenate
numeric values with strings, or represent decimal places in numbers that were initialized
as integer values.
This tutorial will guide you through converting numbers, strings, tuples and lists, as well
as provide examples to help familiarize yourself with different use cases.
You can also use this with a variable. Lets declare f as equal to 57, and then print out
the new float:
f = 57
print(float(f))
Output
57.0
When converting floats to integers with the int() function, Python cuts off the decimal
and remaining numbers of a float to create an integer. Even though we may want to
round 390.8 up to 391, Python will not do this through the int() function.
In Python 3, relevant quotients are converted from integers to floats when doing division
though they are not in Python 2. That is, when you divide 5 by 2, in Python 3 you will get
a float for an answer (2.5):
a = 5 / 2
print(a)
Output
2.5
In Python 2, since you were dealing with two integers, you would receive an integer
back as your answer, instead: 5 / 2 = 2. Read Python 2 vs Python 3: Practical
Considerations for more information about the differences between Python 2 and
Python 3.
When running str(12) in the Python interactive shell with the python command in a
terminal window, youll receive the following output:
Output
'12'
The quotes around the number 12 signify that the number is no longer an integer but is
now a string value.
With variables we can begin to see how practical it can be to convert integers to strings.
Lets say we want to keep track of a users daily programming progress and are
inputting how many lines of code they write at a time. We would like to show this
feedback to the user and will be printing out string and integer values at the same time:
user = "Sammy"
lines = 50
print("Congratulations, " + user + "! You just wrote " + lines + " lines
of code.")
Were not able to concatenate strings and integers in Python, so well have to convert
the variable linesto be a string value:
user = "Sammy"
lines = 50
print("Congratulations, " + user + "! You just wrote " + str(lines) + "
lines of code.")
Now, when we run the code, we receive the following output that congratulates our user
on their progress:
Output
Congratulations, Sammy! You just wrote 50 lines of code.
If we are looking to convert a float to a string rather than an integer to a string, we follow
the same steps and format. When we pass a float into the str() method, a string value
of the float will be returned. We can use either the float value itself or a variable:
print(str(421.034))
f = 5524.53
print(str(f))
Output
421.034
5524.53
We can be sure our float was properly converted to a string because the concatenation
was performed without error.
Because the two numeric values were stored in strings, we received an error. The
operand - for subtraction is not a valid operand for two string values.
Lets modify the code to include the int() method that will convert the strings to
integers, and allow us to do math with values these that were originally strings.
lines_yesterday = "50"
lines_today = "108"
lines_more = int(lines_today) - int(lines_yesterday)
print(lines_more)
Output
58
In this case, using the + operand with two strings is a valid operation, but it is
concatenating two strings rather than adding two numeric values together. So, our
output looks unusual since it just places the two values next to each other.
Well want to convert these strings to floats prior to performing any math with
the float() method:
total_points = "5524.53"
new_points = "45.30"
new_total_points = float(total_points) + float(new_points)
print(new_total_points)
Output
5569.83
Now that we have converted the two strings to floats, we receive the anticipated result
that adds 45.30 to 5524.53.
If we try to convert a string value with decimal places to an integer, well receive an
error:
f = "54.23"
print(int(f))
Output
ValueError: invalid literal for int() with base 10: '54.23'
If we pass a decimal value in a string to the int() method well receive an error
because it will not convert to an integer.
Converting strings to numbers enables us to quickly modify the data type we are
working with so that we can perform operations on numeric values that were originally
cast as strings.
Converting to Tuples
Lets start with converting a list to a tuple. Converting a list to a tuple, because its an
immutable data type, can allow substantial optimization to the programs that we create.
When we use the method tuple() it will return the tuple version of the value passed to
it.
print(tuple(['pull request', 'open source', 'repository', 'branch']))
Output
('pull request', 'open source', 'repository', 'branch')
We see that a tuple is printed out in the output, as the items are now contained within
parentheses rather than square brackets.
Lets use tuple() with a variable that represents a list:
sea_creatures = ['shark', 'cuttlefish', 'squid', 'mantis shrimp']
print(tuple(sea_creatures))
Output
('shark', 'cuttlefish', 'squid', 'mantis shrimp')
Again, we see that the list value is changed to a tuple value, indicated by the
parentheses. We can convert any iterable type to a tuple, including strings:
print(tuple('Sammy'))
Output
('S', 'a', 'm', 'm', 'y')
Because we can iterate through strings, we can convert them to tuples with
the tuple() method. With data types that are not iterable, however, like integers and
floats, we will receive a type error:
print(tuple(5000))
Output
TypeError: 'int' object is not iterable
While it is possible to convert the integer to a string and then convert to a tuple, as
in tuple(str(5000)), it is best to opt for readable code over complicated
conversions.
Converting to Lists
Converting values, especially tuples, to lists can be useful when you need to have a
mutable version of that value.
Well use the list() method to convert the following tuple to a list. Because the syntax
for creating a list uses parentheses, be sure to include the parentheses of
the list() method, and in this case the print() method as well:
print(list(('blue coral', 'staghorn coral', 'pillar coral')))
Output
['blue coral', 'staghorn coral', 'pillar coral']
The square brackets signal that a list has been returned from the original tuple value
that was passed through the list() method.
To make the code more readable, we can remove one of the pairs of parentheses by
using a variable:
coral = ('blue coral', 'staghorn coral', 'pillar coral')
list(coral)
Here the string 'shark' was converted to a list, providing a mutable version of the
original value.
Conclusion
This Python tutorial demonstrated how to convert several of the important native data
types to other data types, primarily through built-in methods. Being able to convert data
types in Python provides you with extra flexibility when writing your programs.