(一)1-5Python数字和字符串

作业
一、数字数据类型用于存储数值。它们是不可变数据类型。
  a = 3.0
  b = 2.5
  c = 2.4
Python支持不同的数值类型
  1、init(有符号整数) - 它们通常被称为整数或整数。它们是没有小数点的正或负整数。
  2、float(浮点实数值) - 也称为浮点数,它们表示实数,并用小数点写整数和小数部分。
数字类型转换
Python可将包含混合类型的表达式内部的数字转换成用于评估求值的常用类型。 有时需要从一个类型到另一个类型执行明确数字转换,以满足运算符或函数参数的要求。
  ● int(x)将x转换为纯整数。
  ● long(x)将x转换为长整数。
  ● float(x)将x转换为浮点数。
数学函数
  1、abs(x) x的绝对值,x与零之间的(正)距离。
  2、round(x,n) 返回浮点数x的四舍五入值。
  c = 2.555
  d = 1.545
  print(round(c,2))
  print(round(d,2))
运行结果:
  2.56
  1.54
二、python布尔类型对应两个布尔值:True和False,分别对应1和0。

  print(True == 1)
  print(False == 0)
  print(True + False + 520)
运行结果:
  True
  True
  521

三、字符串是 Python 中最常用的数据类型。我们可以使用引号('或")来创建字符串。
1、Python不支持字符类型; 字符会被视为长度为1的字符串,因此也被认为是一个子字符串。要访问子串,请使用方括号的切片加上索引或直接使用索引来获取子字符串。 例如 -

    str1 = "abbstrbcdestrfghistrjklmn"
  print(str1[0],str1[1], str1[2],str1[3])
运行结果:
  ('a', 'b', 'b', 's')


str1 = "abbstrbcdestrfghistrjklmn"

2、 字符串find()方法
  print(str1.find("str"))
运行结果:
  3
3、 字符串replace()
  print(str1.replace("str","STR"))
运行结果:
abbSTRbcdeSTRfghiSTRjklmn
4、 字符串split() shell 里面的awk 的-F 的选项
  print(str1.split("str"))
运行结果:
  ['abb', 'bcde', 'fghi', 'jklmn']

5、字符串join()
  print('hello '.join(str1.split('str')))
运行结果:
  abbhello bcdehello fghihello jklmn
6、 字符串strip()
  b = ' adrffgf dffs adff '
  print(b.lstrip())
  print(b.strip())
运行结果:
  adrffgf dffs adff (末尾有空格)
  adrffgf dffs adff(末尾没空格)

7、 字符串format()
  name = "cnblogs"
  url = "www.cnblogs.com"
  print("hello " + name )
  print("hello %s" % name)
  print("hello {0},url is: {1}".format(name,url))
运行结果:
  hello cnblogs
  hello cnblogs
  hello cnblogs,url is: www.cnblogs.com
8、三重引号
  Python中的三重引号允许字符串跨越多行,包括逐字记录的新一行,TAB和任何其他特殊字符。

  

原文地址:https://www.cnblogs.com/pythonlx/p/7712470.html