Functions: Type Conversion
This section will cover converting between different types of data, the first of which is text and relies on the American Standard Code for Information Interchange, or ASCII for short. In recent years, Unicode has become more common as it represents many more characters and is the standard in Python 3, but if you need to use the
ascii() function, you can pass it some text and it will tell you what can be represented in ASCII.
00:36 In this case, the text can be represented in ASCII because all the characters are there, but if we pass it some Unicode text with a different character set as you can see onscreen here, it escapes them in a similar way as we’ve seen earlier and gives us character codes that represent those.
00:53 This can be useful if you have a system which can only represent character codes that are in ASCII, but it’s still possible to store these characters in an ASCII format that would then translate back to Unicode.
And as we can see, that returns a Unicode string of one character. So, the ordinal is put in. In this case,
97 equates to a lowercase
98 equates to a lowercase
65 equates to a capital
01:57 So for instance, capital A is 64 + 1, which is 65 and lowercase a is 96 + 1, which is 97. You can probably see how the two alphabets mirror each others’ layouts, and how from 32 up to 63 there are numbers and punctuation characters, and from 0 to 31 there are a set of control characters which aren’t commonly used anymore but are implemented in some systems. Now, there isn’t a table for the Unicode character set because it’s much larger—it’s got millions of characters in, so that would take many screens.
chr() has a complimentary function
ord(), where you can pass it a single character—such as the
'a' that we’ll see here—and it will tell you what the ASCII or Unicode point for that is, remembering that ASCII codes are the same as Unicode below 128.
Another function you’ve already seen is
type() can be fed any object, whether it’s an explicit declaration or a variable, and it will tell you what type that is, such as
04:13 Generally, this is useful for when exploring variables and objects, but it’s probably not something you should use typically in your code. There are a number of conversion functions that we’ve already seen earlier on in this series, but we’re just going to take a quick recap on those as they’re so useful.
In a complex number, if we pass it just a single
int, we get
4 real numbers and
0 on the imaginary plane, but you can also define it in the normal way, using
4+3j in this case, and there you can see your complex number.
Become a Member to join the conversation.