Python数字类型及字符串类型的内置方法 ##

数字类型及字符串类型的内置方法

数字类型

数字类型有哪些?

整型和浮点型

有哪些运算符?

平时用的加减乘除、整除、模运算、幂运算,比较运算等

他们的属性?

数字类型没有有序,无序一说。换言之,不存在索引这个概念

数字类型属于不可变数据类型。换言之,如果值发生变化,内存地址也会变化

字符串类型(重点)

一些特殊定义:

r'原生字符串,里面的\n没有换行的意思'
b'010101010101' # 二进制编码的字符串
u'unicode' # unicode编码的字符串

用索引取值

name = 'i am an apple.'
print(name[0])
print(name[1])
print(name[10])
name[1] = 'b' #这行代码会报错,记住,按索引取值,只能取,不能赋值

切片取值

hello = 'hello world!'
print(hello[3:])  # 从索引3切到最后
print(hello[3:5])  # 从索引3切到索引5,包括索引3,但不包括索引5,俗称“顾头不顾尾”
print(hello[3:10:2])  # 从索引3切到索引10,补偿为2,即每次跳2个索引
print(hello[:])  # 切了全部内容,相当于什么也没变化
print(hello[::-1])  # 反转切片。步长-1,表示倒叙切片
print(hello[-2:-5:1])  # 思考下,为什么这切片,切出来的东西是空的
print(hello[-2:-5:-1])  # 从-2反向切到-5,但不包括-5的值

len方法

hello = 'hello world!'
apple = 'i like apple really.'
question = 'Do you know how long is my height?'
print(len(hello))
print(len(apple))
print(len(question))
# it can show your length instant

in & not in

hello = 'hello world!'
apple = 'i like apple really.'
print('hello' in hello)  # 判断变量hello里是否有‘hello’,如果有,返回True
print('apple' not in apple)  # 判断变量apple是否“没有‘apple’”,如果没有返回True

strip lstrip rstrip

blank = '   i do not want so many blanks on my heads and tails.    '
print(blank.strip())  # 清除左右两边的对应字符。若空,表示去除空格
print(blank.lstrip())  # 清除左边的空格,即头
print(blank.rstrip())  # 清除右边的空格,即尾

split rsplit

# split,通过指定字符把字符串切换成列表(不包括原来的指定字符)
apple = 'iphone imac ipad iwatch macpro'
fake_news = 'cnn:new york times:fox news net'
print(apple.split())  # 没有指定字符串,则默认是空格,相当于默认是' '
print(fake_news.split(':'))  # 指定了“:”,则用“;”来进行分割
# 自己查看下面2组代码运行结果的不同,体会下split和rsplit的区别
print(apple.split(' ', 2))
print(apple.rsplit(' ', 2))

循环

apple = 'iphone imac ipad iwatch macpro'
for i in apple:
    print(i)
# 使用for遍历字符串中所有字符

upper & lower

need_lower = 'I need be Lowercase.'
need_upper = 'i need be capital style.'
print(need_lower.lower())
print(need_upper.upper())

startswith and endswith

person = 'you and i'
print(person.startswith('you'))
print(person.endswith('i'))
# 判断字符串是否以指定字符开始或结尾。返回True或False

join

# join方法,把字符串插入一个字符串列表之间,返回新的字符串
apple_products_list = ['iphone', 'macbook', 'imac', 'ipad', 'iwatch']
print(':'.join(apple_products_list))

replace

teacher = 'Nick is shuai'
print(teacher.replace('shuai', 'handsome'))

猜你喜欢

转载自www.cnblogs.com/heroknot/p/10912839.html