# 本文件介绍字符串的常见用法
name = "zhalslssl"
"""
1.变大写,小写
"""
name_big = name.upper()
print(name_big)
name_small = name.lower()
print(name_small)
"""
2.判断是否是数字
"""
v1 = "123"
res = v1.isdecimal()
print(res)
v2 = "qwer"
res = v2.isdecimal()
print(res)
"""
3.判读是否以xx开头/结尾
"""
test = "Jajoe"
res = test.startswith("J")
print(res)
"""
4.替换
"""
test = "中国联通"
res = test.replace("中国", "山东")
res_agin = res.replace("山东", "济南")
print(res_agin)
"""
5.切割,将字符串转换为列表
"""
text = "jx,19,gqd"
res = text.split(",")
print(res)
for item in res:
print(item)
"""
6.连接,将列表转换为字符串
"""
text_list = ["哈哈", "喜喜", "拉拉"]
res = "-".join(text_list)
print(res)
"""
7.去除空白,不只是空格,换行也可以,字符串中间有空格不行,要用replace
"""
text = " 哈哈是我的神 " \
" "
data = text.strip()
print(data)
""""
------------------------------------------------------------------------------------------------------------------------
公共功能
1.长度
"""
name = "lalal"
v1 = len(name)
print(v1)
"""
2.索引
"""
data = name[0]
print(data)
"""
3.切片
"""
name = "中国山东浙江江苏广州"
data = name[0:]
data1 = name[:-1]
data2 = name[2:5]
data3 = name[::-1]
print(data, data1, data2, data3)
print("{}*{}*{}--{}".format(data, data1, data2, data3))
"""
4.判断字符串是否在某个序列中
"""
text = "中国上海北京济南承德重庆成都深圳"
v1 = "上海" in text
print("上海在text中是{}".format(v1))
""""
总结:
字符串独有功能:
1.变大小写:upper,lower
2.是否是数字 isdecimal
3.判断是否是以xx开头/结尾 startswith,endswith
4.替换 replace
5.切割 split
6.连接 join
7.去除空白 strip
公共功能:
1.长度 len
2.索引 name[0]
3.切片 name[::-1]
4.判断字符串是否在某个序列中 ""in xxx
"""
"""
练习
1. 计算国字出现的次数
"""
text = input("请输入一段文本")
text = text.strip()
count = 0
for item in text:
if item == "国":
count += 1
print("总共出现的次数是{}".format(count))
"""
2.提示用户输入文本含有字母数字,并将数字提取出来
"""
num = input("请输入数字")
num = num.strip()
result = ""
for item in num:
if item.isdecimal():
result = result + item
print(result, type(result))
python字符串常见用法自用
于 2022-12-05 08:22:19 首次发布