3

1-数字与字符串

 3 years ago
source link: https://blog.csdn.net/weixin_45128456/article/details/111376537
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

整数

  • python2 支持int、long
  • python3 支持int

浮点数

  • float 精度为16位

计算符号
/

  • python2:整数表示取整 (9/4 =>2)小数表示除 (9.0/4=>2.25)
  • python3:表示除 (9/4 =>2.25)

// 取整

  • python3:表示取整 (9//4 =>2)

% 取余

  • 9%4 取余数=>1

**

  • 2**4 表示2的4次方==>16

常用函数

  • round(算式,n)保留n位小数位,且自动四舍五入

2、字符串

单引号、双引号、三引号

  • 单引号、双引号都可
  • 如果字符串本身有单引号,外面可以用双引号来表示这个字符串
  • 如果字符串本身有双引号,外面可以用单引号来表示这个字符串
  • 三引号由三个单引号组成、也可由三个双引号组成(三引号中会保留回车)
    eg:print(’’'第一节
    第二节‘’‘)
    打印==》第一节
    第二节
  • \n换行符 \t 制表符

字符串的拼接

  • 加号+ 字符串之间用+进行拼接
    str1=‘我是’
    str2=’哈德森‘
    print(str1+str2)
  • 乘号* 字符串与数字之间用* 表示若干个字符串
    str1=‘我是’
    num1=3
    print(str1*num1)
    ==>我是我是我是
  • 类型不同进行拼接,报错
    str=‘我是’
    num=18
    print(str+num)
    ==>报错
    修改方法:① 给数值加引号:num=’18‘ ② 使用str()函数:print(str+str(num))

数据类型转换

  • type()函数 查看数据类型
  • int()函数 转int类型
  • float()函数 转float类型
  • str()函数 转str类型

屏蔽转义符\n实例
print(‘c:\note1.txt’)
==>c:
ote1.txt
原因:\n代表换行

修改方案①:\n前加
print(‘c:\note1.txt’)
修改方案②:在字符串的外面加r,表示后面的字符串中的转义符全都不生效
print(r’c:\note1.txt’)
修改方案③:用/ 代替\ 正斜杠代表反斜杠
print(‘c:\note1.txt’)

字符串的下标
str1=’abcd‘
打印b
==>print(str1[1])
或print(str1[-3])

字符串的切片 [起始值:终止值:步长]
① 取部分值
str1=’abcd‘
打印bc
==>print(str1[1:3])
或print(str1[-3:-1])

② 取剩余全部值
str1=’abcd‘
打印bcd
==>print(str1[-3:])

步长默认为:1
abcd
[:] 从起始值取到后面所有值 =>abcd
[::2] 从起始值取到后面所有值,步长为2 =>ac

步长为负
abcd
[::-1] 反转字符串 =>dcba
打印cb
[-2:-4:-1] 从起始值取到后面所有值,步长为2 ==>ac


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK