Day 2 – 理解数据类型和字符串操作

Day 2 – 理解数据类型和字符串操作

温馨提示:本文最后更新于2024-12-09 15:03:56,某些文章具有时效性,若有错误或已失效,请在下方留言

基本数据类型

String

字符串下标

字符串的下标 Subscripting可以提取字符串特定位置的字符。

# 提取第一个字符
print("Hello"[0]) # H
# 提取最后一个字符
print("Hello"[len("Hello") - 1]) # o

Python的下标也支持负数,-1 代表最后一个字符,-2 代表倒数第二个字符。

print("Hello"[-1]) # o

Integer

整数类型

# Integer = Whole Number
print(123 + 345) # 468

# Large Integers
print(123_456_789) # 123456789

Float

浮点数有小数点

# Floating Point Number
print(3.1415) # 3.1415

Boolean

Boolean 类型只有两个值 TrueFalse

print(True) # True
print(False) # False

类型检测

类型检测可以使用type()函数

print(type(123)) # <class 'int'>
print(type("123")) # <class 'str'>
print(type(123.34)) # <class 'float'>
print(type(True)) # <class 'bool'>

类型转换

将变量从一个类型转换为另一个类型。

  • 转换为 float 类型:float()
  • 转换为 int 类型:int()
  • 转换为 string 类型:str()
  • 转换为 bool 类型:bool()
int("123") # 123
float("123.33") # 123.33
str(234) # "234"

算数运算符

Python 中常见的算数运算符+ - * / // **/运算符得到的结果是 float 类型,// 运算法得到的结果是 int 类型,相当于取整运算,删除小数点以及后边的结果。

print(123 + 456) # 579
print(7 - 3) # 4
print(3 * 2) # 6
print(6 / 3) # 2.0
print(6 // 3) # 2
print(2 ** 3) # 8 等价于 2 * 2 * 2

数学运算符的优先级遵循PEMDAS

  • P: Parentheses 括号 ()
  • E: Exponents 指数 **
  • MD: Multiplication/Division 乘/除 * /
  • AS: Addition/Subtraction 加/减 + -
print(3 * 3 + 3 / 3 - 3) # 7.0

数字操作

四舍五入

Python 中 round(number, ndigits) 函数用于四舍五入。

  • number: 要四舍五入的数字
  • ndigits:要保留的小数点位数
print(round(3.542)) # 4
print(round(3.542, 2)) # 3.54

复合操作

常见的复合操作+= -= *= \=

score = 0
score += 1
print(score) # 1

f字符串

使用 f 字符串可以在字符串中插入变量,其中变量使用{} 包裹

score = 0
height = 1.8
is_winning = True

print(f"Your score is = {score}, your height is {height}. You are winning is {is_winning}")
# Your score is = 0, your height is 1.8. You are winning is True
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容