Data Types - Numbers and Strings
While reading this course series, you should type in and run the teacher’s course code in your own Python environment to deepen your understanding.
I. Numeric Types
1. Numeric Types int and float
In Chapter 1, User Interaction, we introduced the basic data types. This chapter mainly covers how to use the different data types and explores them in depth.
数字类型即变量的值,如 age = 18,18则是我们保存的数据。
变量的是用来反映/保持状态以及状态变化的,毫无疑问针对不同的状态就应该用不同类型的数据去标识
A numeric type can store only one value and is an immutable type (immutable types are hashable; hashing will be explained in a later chapter).
# int: integer type, whole numbers
定义:age=10 # age=int(10)
用于标识:年龄,等级,身份证号,qq号,个数
# float: floating-point type, numbers with a decimal point
定义:salary=3.1 #salary=float(3.1)
用于标识:工资,身高,体重,
2. Common Methods of the int Type
The bin(), oct() and hex() used in the code below are frequently used for base conversion; it’s worth getting to know them:
# Common operations + built-in methods
print(bin(3)) # Convert decimal to binary, 0b11
print(oct(8)) # Convert decimal to octal, 0o10
print(10) #10
print(hex(16)) # Convert decimal to hexadecimal, 0x10
When writing user-interaction programs, we often use .isdigit() to check whether the user’s input is a number before moving on to the next step, which prevents the program from crashing. Note, however, that user input is a string by default; to check whether a string is a number, we use this method.
age = input(“your age>>:”)
if age.isdigit(): # isdigit() checks whether the string consists only of digits
age = int(age)# If you type code in PyCharm, the line under the if statement is indented automatically; in an ordinary text editor,
敲下'Tab'键就可以缩进
age +=1
print(age)
3. Other Python Numeric Types (for reference)
#int (integer)
在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
#long (long integer)
跟C语言不同,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,
但实际上由于机器内存有限,我们使用的长整数数值不可能无限大。
注意,自从Python2.2起,如果整数发生溢出,Python会自动将整数数据转换为长整数,
所以如今在长整数数据后面不加字母L也不会导致严重后果了。
注意:在Python3里不再有long类型了,全都是int
>>> a= 2**64 # >>> means input in command-line mode
>>> type(a) #type() is the method for checking a data type
<type 'int'># int type
>>> b= 2**60
>>> type(b)
<type 'int'>
#complex: complex number type
>>> x=1-2j
>>> x.imag
-2.0
>>> x.real
1.0
II. String Type
1. Introduction to the String Type
In Python, characters enclosed in quotes are of the string type. They are used to represent descriptive content, such as name, gender, nationality, ethnicity. They are defined like this:
name='Albert' # name=str(Albert)
#'Albert' and "Albert": both forms are strings
# str() can convert other data types into strings
String formatting:
name = input('请输入名字>>:') #'请输入名字' is a string
print('你好,%s' % name)# %s can be thought of as a placeholder; on output it is replaced with the value of the variable after the % following the string
2. The Difference Between Single, Double and Triple Quotes
#So what's the difference between single quotes, double quotes, and multiple quotes? Let me tell you loud and clear: there's no difference at all between single and double quotes,
只有下面这种情况 你需要考虑单双的配合
msg = "My name is Albert , I'm 18 years old!"
#What are multiple quotes for? Multi-line strings must use multiple quotes
msg =
'''
今天我想写首小诗,
歌颂我的同桌,
你看他那乌黑的短发,
好像一只炸毛鸡。
'''
print(msg)
# Write multi-line content inside triple quotes
3. String Concatenation
#Numbers can be added, subtracted, multiplied and divided. What about strings? Let me tell you loud and clear: they can too? What? Yes, but only "addition" and "multiplication".
>>> name='albert'
>>> age='18'
>>> name+age # Addition, simple concatenation
'albert18'
>>> name*5
'albertalbertalbertalbertalbert'
#Note 1:
字符串1+字符串3,并不会在字符串1的基础上加字符串3,而是申请一个全新的内存空间存入字符串1和字符串3,
相当字符串1与字符串3的空间被复制了一次
#Note 2: You can only add a string to a string, not a string to another type
字符串拼接(只能在字符串之间进行,且只能相加或相乘)
A string type can store only one value, is an immutable type, and is hashable.
4. Common Methods of the String Type
(1) Accessing Values by Index
Strings are immutable, so you cannot change a string’s value. When accessing values you can pass up to three parameters: the start position, the end position and the step. You can access values forward or in reverse (when the start position is greater than the end position, or there is no start or end position; a step of -1 means starting from the last one; the step is negative)
hobbies = "music basketball"
print(hobbies[0])
print(hobbies[1])
print(hobbies[5])
print(hobbies[0:5])
print(hobbies[:5])
print(hobbies[0:5:2]) # From element 0 to element 4, taking every other element
print(hobbies[0:5:-2])# No elements are returned, because this means from element 0 to element 4, in reverse order (-2 is negative), taking every other element;
第零个元素前面没有元素了,所以什么都取不出来
print(hobbies[11:5:-2])# From element 11 to element 6, in reverse order, taking every other element
print(hobbies[-1])# Get the last character
print(hobbies[-2])# Get the second-to-last character
(2) Length
print(len('name'))# Can be used to get the length of a string, a list, etc.
(3) Membership
print('a' in 'Albert')# Checks whether a is in Albert; returns True if so, otherwise False
# False
print('a' not in 'Albert')
# True
(4) Removing Whitespace
print(' name'.lstrip()) # Remove whitespace on the left
print('name '.rstrip()) # Remove whitespace on the right
print(' name '.strip()) # Remove whitespace on both sides
(5) Splitting
What splitting is for: for example, given a piece of data “Kobe 24 Lakers”, you need to extract Kobe’s number and his team. You can split it as follows, and a list will be returned.
print('Kobe 24 Lakes'.split(' '))
print('n a me'.split(','))
print('n,a me'.split(','))
print('n,/a /me'.split('/',1)) # The number is the number of splits; by default it splits everything
print('n,a /me'.split('/'))
print('a|b|c'.rsplit('|',1)) # Split starting from the right
(6) Joining
print('a'.join('1234'))
print('a'.join('bcde'))
tag = ' '
print(tag.join(['I', 'say', 'hello', 'world'])) # The iterable must consist entirely of strings
(7) Replacing
print('abc name id'.replace('a', 'card')) # Replace every a in the preceding string with "card"
name = 'albert say :i have a dream,my name is albert'
# Note that the original value of name is not changed here; instead, a new value is produced after the replacement
print(name.replace('albert', 'Albert', 1))# Replace albert in name with Albert, only once; by default all occurrences are replaced
(8) Other String Operations
# find,rfind,index,rindex,count
name='albert say hello'
print(name.find('o',1,3)) # Includes the start but not the end; returns -1 without raising an error if not found, shows the index if found
# print(name.index('e',2,4)) # Same as above, but raises an error if not found
print(name.count('e',1,3)) # Includes the start but not the end; if no range is specified, searches everything
# center,ljust,rjust,zfill
name='albert'
print(name.center(30,'-'))
print(name.ljust(30,'*'))
print(name.rjust(30,'*'))
print(name.zfill(50)) # Pad with 0
# captalize,swapcase,title
print(name.capitalize()) # Capitalize the first letter
print(name.swapcase()) # Swap upper and lower case
msg='albert say hi'
print(msg.title()) # Capitalize the first letter of each word
# The is-number family
# In python3
num1=b'4' # bytes
num2=u'4' # unicode; in python3 strings are unicode without the u
num3='四' # Chinese numeral
num4='Ⅳ' # Roman numeral
# isdigit:bytes,unicode
print(num1.isdigit()) # True
print(num2.isdigit()) # True
print(num3.isdigit()) # False
print(num4.isdigit()) # False
# isdecimal:uncicode
# The bytes type has no isdecimal method
print(num2.isdecimal()) # True
print(num3.isdecimal()) # False
print(num4.isdecimal()) # False
# isnumberic: unicode, Chinese numerals, Roman numerals
# The bytes type has no isnumberic method
print(num2.isnumeric()) # True
print(num3.isnumeric()) # True
print(num4.isnumeric()) # True
# None of the three can recognize floating-point numbers
num5='4.3'
print(num5.isdigit())
print(num5.isdecimal())
print(num5.isnumeric())
'''
总结:
最常用的是isdigit,可以判断bytes和unicode类型,这也是最常见的数字应用场景
如果要判断中文数字或罗马数字,则需要用到isnumeric
'''
# Other is-methods
print('===>')
name='alb123ert'
print(name.isalnum()) # The string consists of letters or digits
print(name.isalpha()) # The string consists only of letters
print(name.isidentifier())
print(name.islower())
print(name.isupper())
print(name.isspace())
print(name.istitle())