当前位置:网站首页>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/
边栏推荐
- Global and Chinese market of two in one notebook computers 2022-2028: Research Report on technology, participants, trends, market size and share
- 2022-06-27 advanced network engineering (XII) IS-IS overhead type, overhead calculation, LSP processing mechanism, route revocation, route penetration
- Chapter 1: King Shehan miscalculated
- 4. Data splitting of Flink real-time project
- Acquisition and transmission of parameters in automatic testing of JMeter interface
- MPLS configuration
- Cesiumjs 2022 ^ source code interpretation [7] - Analysis of the request and loading process of 3dfiles
- Global and Chinese markets of active matrix LCD 2022-2028: Research Report on technology, participants, trends, market size and share
- Strict data sheet of new features of SQLite 3.37.0
- Sword finger offer 30 Stack containing min function
猜你喜欢

Chapter 1: simplify the same code decimal sum s (D, n)

Sparse matrix (triple) creation, transpose, traversal, addition, subtraction, multiplication. C implementation

第一章:简化同码小数和s(d, n)

Popularize the basics of IP routing

PR 2021 quick start tutorial, material import and management

NFT without IPFs and completely on the chain?

Native table - scroll - merge function

2022-06-30 網工進階(十四)路由策略-匹配工具【ACL、IP-Prefix List】、策略工具【Filter-Policy】

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

IPv6 experiment
随机推荐
Exercises of function recursion
Microservice knowledge sorting - search technology and automatic deployment technology
How to improve data security by renting servers in Hong Kong
第一章:求n的阶乘n!
HCIA-USG Security Policy
02 -- QT OpenGL drawing triangle
FAQs for datawhale learning!
Don't be afraid of no foundation. Zero foundation doesn't need any technology to reinstall the computer system
2022-06-30 网工进阶(十四)路由策略-匹配工具【ACL、IP-Prefix List】、策略工具【Filter-Policy】
2022-06-27 网工进阶(十二)IS-IS-开销类型、开销计算、LSP的处理机制、路由撤销、路由渗透
About unregistered transfer login page
Microsoft: the 12th generation core processor needs to be upgraded to win11 to give full play to its maximum performance
03 -- QT OpenGL EBO draw triangle
FPGA 学习笔记:Vivado 2019.1 工程创建
[effective Objective-C] - block and grand central distribution
PR FAQ: how to set PR vertical screen sequence?
2022-06-30 advanced network engineering (XIV) routing strategy - matching tools [ACL, IP prefix list], policy tools [filter policy]
Global and Chinese market of rubidium standard 2022-2028: Research Report on technology, participants, trends, market size and share
2022-07-02 网工进阶(十五)路由策略-Route-Policy特性、策略路由(Policy-Based Routing)、MQC(模块化QoS命令行)
4. Data binding