你要偷偷学Python,然后惊艳所有人(字符串)

字符串的常用操作

hello_str="hello hello"
#统计字符串长度
print(len(hello_str))
#统计字符串中某个子字符出现的次数
print(hello_str.count('he'))
#字符串中某一个子字符串第一次出现的位置
print(hello_str.index("e"))
#结果

11
2
1

在这里插入图片描述

#1、判断空白字符,\n,\r,\t也属于空白字符
space_str=" \n\r\t  "
print(space_str.isspace())
#结果
True

#2、判断字符串是否都是由数字或字母构成的
isalnum_str1="abcd123"
isalnum_str12="abcd 123"
print(isalnum_str1.isalnum())
print(isalnum_str12.isalnum())
#结果
True
False

#3、判断字符串是否都是由字母构成
alpha_str1="abcde"
alpha_str2="abcd123"
print(alpha_str1.isalpha())
print(alpha_str2.isalpha())
#结果
True
False

#4、判断字符串中是否只包含数字
#主要有三个方法 isdecimal()、isdigit()、isnumeric()
#这三个方法都不能判断小数
#isdigit()、isnumeric()可以判断unicode字符串
#isnumeric()可以判断中文数字
num_str1="123"
num_str2="\u00b2"
num_str3="一千零一"
print(num_str1.isdecimal(),num_str2.isdecimal(),num_str3.isdecimal())
print(num_str1.isdigit(),num_str2.isdigit(),num_str3.isdigit())
print(num_str1.isnumeric(),num_str2.isnumeric(),num_str3.isnumeric())
#结果
True False False
True True False
True True True

#判断string标题化的(每个单词的首字母大写)则返回True
istitle_str1="This is a tiltle"
istitle_str2="This Is A Tiltle"
print(istitle_str1.istitle())
print(istitle_str2.istitle())
#结果
False
True

#判断字符串中的英文是否都是小写
lower_str1="123 is number"
lower_str2="123 is Number"
print(lower_str1.islower())
print(lower_str2.islower())
#结果
True
False

#判断字符串中的英文是否都是大写
upper_str1="123 is number"
upper_str2="123 IS NUMBER"
print(upper_str1.isupper())
print(upper_str2.isupper())
#结果
False
True

在这里插入图片描述

#1、判断是否以指定字符串开始
hello_str1="hello hello"
hello_str2="hahahahaha"
print(hello_str1.startswith("hello"))
print(hello_str2.startswith("hello"))
#结果
True
False

#2、判断是否以指定字符串结束
hello_str1="hello hello"
hello_str2="hahahahaha"
print(hello_str1.endswith("llo"))
print(hello_str2.endswith("llo"))
True
False

#3、查找指定字符串、返回的是一个索引位置,找不到则返回-1
hello_str1="hello hello"
hello_str2="hahahahaha"
print(hello_str1.find("ello"))
print(hello_str2.find("abc"))
#结果
1
-1

#4、替换字符串
#replace方法,会返回一个新的字符串,并不会替换旧字符串
hello_str="hello hello world"
hello_str2=hello_str.replace("hello","hi")
print(hello_str)
print(hello_str2)
#结果
hello hello world
hi hi world

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

strip_str="  \t abc def gg   "
print(strip_str.strip())
print(strip_str.lstrip())
print(strip_str.rstrip())
#结果
abc def gg
abc def gg   
  	 abc def gg

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值