当前位置:网站首页>2.5 conversion of different data types (2)
2.5 conversion of different data types (2)
2022-07-03 20:00:00 【leeshuqing】
Continue to introduce the conversion of different data types . Let's take a look at the conversion between strings and integers .
First, let's look at the conversion between integer and single character . Let's start with a question , First of all, make it clear , The two cannot be mixed .

More common errors occur in the processing of input data .
num = input()
print(num + 1)
The operation interface is :

At this time, no matter what value is entered , Will produce the same error , It means that you can only connect strings with strings ( That is to add ).
Correct handling can be used int function :
num = input()
num = int(num)
print(num + 1)
The operation interface is :

in addition to , There is also a special conversion method , That is, convert a single character to the corresponding integer encoding .
strs = 'A'
print(ord(strs))Output is :65. there ord The function returns the sequence number code corresponding to the character ,ord by ordinal( Serial number ) It means , Capital A The serial number code of is 65. Why? A Corresponding 65 Serial number ? This sequence number encoding is often referred to as a character set , Each common character corresponds to a unique sequence number . Different character sets may have different correspondence , But English characters are usually the same , Common character sets are ASCII、Unicode etc. .
This is a common character encoding :

Here for beginners , There is often a problem , Is the number 0 And integer 0 The difference between . Through the current character encoding , We can make an accurate distinction , In terms of integers , character 0 It's actually 48, Judging from the characters , Integers 0 It's actually a blank character .
Why should characters correspond to coding sequence numbers ? In the computer data storage structure , In fact, it can only store integers and floating-point numbers , Characters and Booleans cannot be stored directly . therefore , Computers usually express these types in a way of code mapping . For example, for characters , The computer can only store the serial number corresponding to these characters , This is an integer , If you need to convert to characters when reading , So the computer will look up the corresponding characters in the character coding table , And display the character .

The same is true for Booleans , What is really stored is 0 and 1 Two kinds of integers , Also through simpler encoding conversion ,0 Convert to False,1 Convert to True To realize the display of Boolean data .

Chinese characters also have coding numbers .
strs = ' south '
print(ord(strs))
Output is :21335.
In turn, , We can also use it chr Function converts an integer to a character , Is converted to the corresponding encoded characters .
num = 65
print(chr(num))
Output is :A.
Master these methods , We can use this integer encoding to skillfully convert characters . For example, change uppercase to lowercase :
strs = 'Z'
print(chr(ord(strs) + 32))Output is :z. Here are lowercase letters “z”, The difference between the codes of upper and lower case letters is 32, Therefore, the case conversion can be realized by encoding the difference and accumulating the conversion .
Even if you don't know how much the case difference is , We can still finish :
strs = 'Z'
print(chr(ord(strs) + ord('a') - ord('A')))The output content is the same as . You can experience the ingenious use of integers and characters for conversion .
Of course , It is simpler to use the existing lower case conversion function of string lower:
strs = 'Z'
print(strs.lower())
The output content is the same as .
For strings containing multiple numeric characters , You can also use int and str Functions directly convert to and from integers . Such as through int Function can directly convert a numeric string to the corresponding integer :
strs = '1234'
print(int(strs) + 1)Output is :1235.
adopt str Function can directly convert an integer to the corresponding string :
num = 1234
print(str(num) + '1')Output is :12341.
str It can also be used in other types of string conversion , Such as floating point numbers and Booleans :
num = True
print('[' + str(num) + ']')Output is :[True].
because str The default is the name of the character conversion function , Therefore, it is suggested that when defining variables , Don't use str, Or in use str Function , Please try to avoid using str The definition form of the same name , Such as :
num = 1234
strs = str(num)
print(strs)
If you use str As a variable name, there may be problems , Such as :
num = 1234
str = 'ABCD'
print(str(num))
The operation interface is :

The error here is that the last line was intended to be converted num For the string , however str Functions and str Variable with the same name , In this time str Function failure , Of course, the last line can't depend on str String variable ‘ABCD’ To complete the real type conversion .
Speaking of this , We can understand the comparison of characters , In fact, it is the comparison of character encoded integers . such as :
str1 = 'A'
str2 = 'a'
print(str1 < str2)Output is :True.
If it is a string with multiple characters , The comparison rule is to compare characters one by one from left to right , Once there is a character compared to the size , The comparison ends and takes this result as the size comparison result of the string , Be similar to 1 Yes 1 Penalty match :

such as :
str1 = 'aAaaa'
str2 = 'b'
print(str1 < str2)Output is :True, Because the result of the first character comparison shows that the second string is larger .
But if two strings are compared , The front is consistent , There is another string and more characters , Then it is bigger :
str1 = 'aAaaa'
str2 = 'aAa'
print(str1 > str2)
Output is :True.
Supporting learning resources 、 MOOC video :
Python Big data analysis - Shu Qing Li
https://www.njcie.com/python/
边栏推荐
- NFT without IPFs and completely on the chain?
- P5.js development - setting
- 3. Data binding
- Global and Chinese markets for medical temperature sensors 2022-2028: Research Report on technology, participants, trends, market size and share
- Pat grade B 1009 is ironic (20 points)
- 第一章:求所有阶乘和数,大奖赛现场统分程序设计,三位阶乘和数,图形点扫描,递归求n的阶乘n!,求n的阶乘n!,舍罕王失算
- Promethus
- Micro service knowledge sorting - three pieces of micro Service Technology
- Phpstudy set LAN access
- HCIA-USG Security Policy
猜你喜欢

Typora charges, WTF? Still need support

The 15 year old interviewer will teach you four unique skills that you must pass the interview

IP address is such an important knowledge that it's useless to listen to a younger student?

Chapter 20: y= sin (x) /x, rambling coordinate system calculation, y= sin (x) /x with profile graphics, Olympic rings, ball rolling and bouncing, water display, rectangular optimization cutting, R que

Chapter 1: seek common? Decimal and S (D, n)

kubernetes集群搭建efk日志收集平台

Xctf attack and defense world crypto advanced area best_ rsa

第二章:4位卡普雷卡数,搜索偶数位卡普雷卡数,搜索n位2段和平方数,m位不含0的巧妙平方数,指定数字组成没有重复数字的7位平方数,求指定区间内的勾股数组,求指定区间内的倒立勾股数组
![2022-06-30 advanced network engineering (XIV) routing strategy - matching tools [ACL, IP prefix list], policy tools [filter policy]](/img/b6/5d6b946d8001e2d73c2cadbdce72fc.png)
2022-06-30 advanced network engineering (XIV) routing strategy - matching tools [ACL, IP prefix list], policy tools [filter policy]

Point cloud data denoising
随机推荐
Difference between surface go1 and surface GO2 (non professional comparison)
How to check the permission to write to a directory or file- How do you check for permissions to write to a directory or file?
PR 2021 quick start tutorial, how to create a new sequence and set parameters?
Day11 - my page, user information acquisition, modification and channel interface
2022-06-30 网工进阶(十四)路由策略-匹配工具【ACL、IP-Prefix List】、策略工具【Filter-Policy】
5- (4-nitrophenyl) - 10,15,20-triphenylporphyrin ntpph2/ntppzn/ntppmn/ntppfe/ntppni/ntppcu/ntppcd/ntppco and other metal complexes
Bright purple crystal meso tetra (4-aminophenyl) porphyrin tapp/tapppt/tappco/tappcd/tappzn/tapppd/tappcu/tappni/tappfe/tappmn metal complex - supplied by Qiyue
Part 28 supplement (XXVIII) busyindicator (waiting for elements)
Chapter 1: recursively find the factorial n of n!
Use unique_ PTR forward declaration? [repetition] - forward declaration with unique_ ptr? [duplicate]
[Yu Yue education] basic reference materials of manufacturing technology of Shanghai Jiaotong University
Global and Chinese market of high temperature Silver sintering paste 2022-2028: Research Report on technology, participants, trends, market size and share
2022 - 06 - 30 networker Advanced (XIV) Routing Policy Matching Tool [ACL, IP prefix list] and policy tool [Filter Policy]
Wechat applet quick start (including NPM package use and mobx status management)
Part 27 supplement (27) buttons of QML basic elements
2022-07-02 网工进阶(十五)路由策略-Route-Policy特性、策略路由(Policy-Based Routing)、MQC(模块化QoS命令行)
4. Data splitting of Flink real-time project
IPv6 experiment
PR 2021 quick start tutorial, how to create new projects and basic settings of preferences?
Popularize the basics of IP routing