首页 > 编程语言 > 详细

python字符串的常见操作

时间:2021-05-20 15:04:23      阅读:28      评论:0      收藏:0      [点我收藏+]
str1 = "hello python"
str2 = "我的外号是‘大蟒蛇‘"

#(1)获取字符串的字符(char)
print(str1[1] ) #e
print(str2[0]) #我

#(2)变量字符串所有的字符
for char in str2:
print(char)

#(3) 字符串的长度
print(len(str1)) #12
print(len(str2)) #10

#(4)查找 子串 出现频率
print(str1.count("l")) ##字符串l出现的频率
print(str1.count("he")) ##字符串he出现的频率

##(5)某一字符(子串) 出现 索引(下标),找到第一个;就停下来了
print(str1.index("l")) ##从走到右边,字符l的下标
print(str1.index("he")) ##从走到右边,字符he的下标

##(6)判断相关的
a = " "
print(a.isspace()) #是否是 空白字符

a = "10086"
print(a.isdecimal()) #True

a = "壹千零一"
print(a.isnumeric()) ##汉字数字

##(7)查找和替换
str1 = "hello python he"
print(str1.startswith("ha")) ##判断是否以什么开头

print(str1.find("python")) ##查找字符,返回下标
print(str1.find("Apython")) ##找不到,返回-1
print(str1.find("he",2)) #从下标为2的位置开始找,到结束
print(str1.find("he",2,8)) #从下标为2的位置开始找,到下标8

print(str1.find("he")) #0
print(str1.rfind("he")) #13

str2 = str1.replace(" ","-") ##不会改变原有的字符串,改变之后 通过返回方式给你
print(str1) #hello python he
print(str2) ##hello-python-he

poem = ["\t\n登鹳雀楼",
"王之涣啊",
"白日依山尽\t\n",
"黄河入海流",
"欲穷千里目",
"更上一层楼"]

for str in poem:
print("| %s |"%str.strip().center(11," "))


#拆分
str1 = "hello python he"
a = str1.split(" ")
print(a)







python字符串的常见操作

原文:https://www.cnblogs.com/ZhaoBa/p/14789263.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!