python内置方法(重点)

方法 作用 示例 输出
upper 全部大写 "hello".upper() "HELLO"
lower 全部小写 "Hello".lower() "hello"
startswith() 是否以a开头 "Yuan".startswith("Yu") True
endswith() 是否以a结尾 "Yuan".endswith("a") False
isdigit() 是否全数字 '123'.isdigit() True
strip() 去两边空格 " hi yuan \n".strip() "hi yuan"
join() 将多个字符串连接在一起 "-".join(["yuan","alvin","eric"]) "yuan-alvin-eric"
split() 按某字符分割字符串,默认按空格分隔 "yuan-alvin-eric".split("-") ['yuan', 'alvin', 'eric']
find() 搜索指定字符串,没有返回-1 "hello world".index("w") 6
index() 同上,但是找不到会报错 "hello world".index("w") 6
count() 统计指定的字符串出现的次数 "hello world".count("l") 3
replace() 替换old为new 'hello world'.replace(‘world',‘python') "hello python"
# 任意数据对象.方法()实现对数据的某种操作
# 不同数据类型对象支持不同方法
# 字符串类型对象支持哪些方法

s1 = "yuan"
s2 = "RAIN"
# (1) upper方法和lower方法
s3 = s1.upper()
s4 = s2.lower()
print(s3) # "YUAN"
print(s4) # "rain"


s5 = "hello yuan"
s6 = "hi world"
# (2) startswith和endswith:判断字符串是否以什么开头和结尾
print(s5.startswith("hello")) # True
print(s6.startswith("hello")) # False
print(s6.startswith("hi wor")) # True
print(s6.endswith("hi wor")) # False

# (3) isdigit(): 判断字符串是否是一个数字字符串
s7 = "123"
s8 = "123A"
print(s7.isdigit()) # True
print(s8.isdigit()) # False
s9 = "123SAA%#"
print(s9.isalnum()) # False 不能包含特殊符号

# (4) strip(): 去除两端空格和换行符号

s10 = " I am yuan "
print(s10)
print(s10.strip())
name = input("请输入姓名>>").strip()
print(name)

# (5) split分割方法: 将一个字符串分割成一个列表
s11 = "rain-yuan-alvin-eric"
print(s11.split("-")) # ['rain', 'yuan', 'alvin', 'eric']

# (6) join方法: 将一个列表中的字符串拼接成一个字符串
names_list = ['rain', 'yuan', 'alvin', 'eric']
s12 = "-".join(names_list) # 用什么分隔符拼接names_list列表
print(s12,type(s12)) # "rain-yuan-alvin-eric"

【5】类型转换

i = int("3")
print(i,type(i)) # 3 <class 'int'>

s = str(3.14)
print(s,type(s)) # 3.14 <class 'str'>
posted @   jhchena  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示