Python3入门与进阶笔记(一):数据类型(基本数据类型、str)

目录

Python的基本类型

Number:数字

int 和 float

进制

bool

str:字符串

\  转义字符、连接下一行

原始字符串

字符串运算

字符串常见函数

字符串格式化

数字格式化


历史:

2000年10月,2.0发布

2008年12月,3.0发布

2020年,宣布停止对2.x的维护

Python的基本类型

Number:数字

int 和 float

       python3中的整型只有int,小数只有float。type函数可以用来查看类型。

       /表示小数除法,例如2/2=1.0,type(2/2)是float。

       //表示整数除法,例如1//2=0,type(1//2)是int。

进制

       二进制:在数字前加0b,例如2(0b10)、3(0b11)

                     bin函数将任意进制转换成二进制,bin(10)显示0b1010、bin(0o7)

       八进制:在数字前加0o,例如8(0o10)、9(0o11)

                     oct函数将任意进制转换成八进制,oct(0x777)、oct(0b111)

       十进制:直接写

                     int函数将任意进制转换成十进制,int(0x777)、int(0b111)

       十六进制:在数字前加0x,例如16(0x10)、31(0x1F)

                     hex函数将任意进制转换成十六进制,hex(0o777)、hex(0b111)

bool

       True和 False 首字母大写。bool函数可以将非空或非0装换成True,空,None或0转换成False。

str:字符串

\  转义字符、连接下一行

原始字符串

字符串运算

拼接:+    "hello"+"world" 形成"helloworld"

         字符串拼接是指将多个字符串合并,形成一个新的字符串

重复:*     "hello"*3 形成“hellohellohello"

下标:[]  "hello"[0]得到'h',"hello"[-1]得到‘o’

         "hello world"[0:4] 得到"hell" ,不包括4

         "hello world"[0:5]得到"hello",不包括5

         "helloworld"[6:]得到"world"

         "helloworld"[-5:]得到"world"

          a = 'hello' a[0]='g' 错误,'str' object does notsupport item assignment

字符串常见函数

str.lower()

str.upper()

str.capitalize():字符串首字母大写

str.title():每个单词的首字母大写

str.swapcase():大小写互相转换

str.lstrip(): 删除左侧空白

str.rstrip():删除右侧空白

str.strip(): 删除两端空白

str.find(): 获取子字符串出现的位置

      str.find(目标串,[开始位置], [结束位置])

      str1 = "Nice to meet you",   str1.find('ee') ==> 9, str1[8]=='m', 查找到返回第一次出现的下标

                                                 ,    str1.find('fg') ==> -1,查找不到返回-1

str.replace():字符串替换

      str.replace(原始串, 目标串, [替换次数])       

       'aaabbbccc'.replace('b', 'df', 2) ==> 'aaadfdfbccc'

字符串格式化

"{} {} you".format("I", "love") ==> 'I love you'

"{2}.{1}.{0}".format("com", 'imooc',"www") ==> 'www.imooc.com'

"{p2}.{p1}.{p0}".format(p0="com", p1='imooc',p2="www") ==> 'www.imooc.com'

数字格式化

format(1234.567, '0.2f') ==> '1234.57'

format(1234.564, '.2f') ==> '1234.56'

type(format(1234.564, '.2f')) ==> <class 'str'>

format(1234.567, ',') ==> '1,234.567'

0后面接整数部分格式化方式,.后面接小数部分格式化方式

format(1234.567, '0,.2f') ==> '1,234.57'

在字符串格式化时,如遇到格式化输出的数字,则需要在{}内加前缀:,之后写上数字格式化语句

"请您向{}账户转账{:0,.2f}元".format(808001, 1234.567) ==> '请您向808001账户转账1,234.57元'

"{}_{:03}.csv".format('hh', 1) ==> 'hh_001.csv',{:03}最少显示3位数,不足补0 ;"{}_{:03}.csv".format('hh', 1111) ==> 'hh_1111.csv';{}_{:03}.csv".format('hh', -1111) ==> 'hh_-1111.csv'

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值