【Python学习笔记】Python字符串、数字类型

本文目录

  • 变量
  • Python数字类型
  • 字符串

上一篇:Python3基础语法

变量

上篇笔记提到过变量,它可以存储值。

a = "One Sweet Orange"
b = 123
print(a)
print(b)

输出
One Sweet Orange
123

上面的示例中,a,b是变量,对应存储的值是字符串 "One Sweet Orange"和整数123。

Python数字类型

Python数字类型分为四种:整数、布尔数、浮点数、复数。

  • 整数,如:1
  • 布尔数,如:True、False
  • 浮点数,如:1.11、3E-10
  • 复数,如:1+2j

字符串

  • 在Python中,用‘’或“”括起来的就是字符串。当我们的字符串中需要有‘时,我们可以用“”把字符串括起来,反之亦然。
"I can't believe it!"
'"STOP!",he said.'
  • ‘’'或"""可以用来表示一个多行字符串。
"""This is my favorite book,
what about you?"""
  • \是转义符,如\n代表换行。
IN:
print('This is my favorite book,\nwhat about you?')

OUT:
This is my favorite book,
what about you?
  • 在字符串前加个 r可以让\不转义。
IN:
print(r'This is my favorite book,\nwhat about you?')

OUT:
This is my favorite book,\nwhat about you?
  • +用来连接字符串。
IN:
print('one'+' sweet '+'orange')

OUT:
one sweet orange
  • *用来重复字符串。
IN:
print('orange '*3)

OUT:
orange orange orange 
  • Python 中的字符串有两种索引方式,从左往右以 0 开始,从右往左以 -1 开始。
IN:
a = 'This is my favorite book, what about you?'
print(a[0]) # 打印第1个字符
print(a[-1]) # 打印最后1个字符

OUT:
T
?
  • Python中的字符串不能改变。
  • Python 没有单独的字符类型,一个字符就是长度为 1 的字符串。
  • 字符串的截取的语法格式如下:变量[头下标:尾下标:步长]
IN:
a = 'This is my favorite book, what about you?'
print(a[0:9:1]) # 前9个字符,区间[0,9)前开后闭,步长取1。
print(a[0:9:2]) # 前9个字符,区间[0,9)前开后闭,步长取2。
print(a[0:9:3]) # 前9个字符,区间[0,9)前开后闭,步长取3。

OUT:
This is m
Ti sm
Tss

学习过程主要借鉴菜鸟教程
欢迎关注,一起学习。
【Python学习笔记】Python字符串、数字类型_第1张图片

你可能感兴趣的:(Python)