内置对象相关方法

内置对象相关方法


常用内置对象的方法

  • String

    • 定义,切片,长度,替换,编列....

  • 列表/元组

    • 定义,使用,循环遍历.....

  • 字典

    • 定义,使用,循环遍历......

  • 集合Set

  • 连接数据库!

  • 各种内置模块

    • os,file,time,json....

字符串String


  • 定义:一串字符!用""或''引起来 字符串是字符串列表,索引从0开始

  • 字符串是字符串的列表,可以通过索引访问,索引从0开始,-1表示最后一个

  • 索引不能操作范围

  • 字符串不可变

  • 编列

  • +表示连接:控制台input()方法输入的内容都是字符串

  • 切片【开始:结束:步长】【::-1】倒序

  • 格式化字符串
name = tom
age = 20
# 方法1.使用占位符格式化
print("名字:%S,年龄:%d"%(name,age))
# 方法2.格式化
print(f"名字:{name},年龄:{age}")
# 方法3.格式化
print("名字:{0}年龄{1}".format(name,age))
  • 转义

\' 转义
	  制表符等于四个空格(tab)

 换行 
 linux换行
 续行
  • chr()

  • 内置方法

    • len(字符串)# 长度

    • chr() 转化为字符 chr(97)---a chr(65)---A

    • ord(字符)转化为对应ASCII编码  ord("A")--->65
    • find(字符)找不到返回-1
    • index(字符)找不到报错
    • replace(“旧字符串",''新字符串")替换
    • splite("字符")拆分 返回列表!
    • lower(字符串)转为小写
    • upper('字符')转为大写
    • strip(字符串)去掉两边空格 rstrip(字符串)去掉右边空格     lstrip(字符串)去掉左边空格
    • not in ”hello“ 判断是否存在
# 赋值
s = "hello"
s[0] ---> 第一个
s[-1] ---->最后一个
# 字符串不可变
s = "helloworld"
s[5] = "w"  # 报错 str not support item assigment

# 遍历
str01 = "hello
for i in hello:
     print(i)
# 编列索引和值
for i,v in enumerate(str01):
     print(f'第{i},个值:{v}')

# 生成a-z
print(chr(random.choice(range(97,123)))
# A-Z
print(chr(random.choice(range(65,91))))

原文地址:https://www.cnblogs.com/yuzui/p/13905174.html