python的字符串操作(一)

本文章为笔者原创,未经允许不得转载

字符串的介绍
a = 100    # 整型
b = "hello world hello python"    # 字符串
c = 'hello world hello python'    # 字符串

总结:双引号或者单引号中的数据,就是字符串

字符串的输出
name = "baobao"
print(name)
字符串的输入
userName = input("请输入用户名:")
print("用户名为:%s" % userName)
password = input("请输入密码:")
print("密码为:%s" % password)
下标(索引)

所谓下标,就是编号,就好比是超市中的储物柜的编号,通过这个编号能找到相对应的存储空间
字符串中的下标的使用:
列表与元祖支持下标索引好理解,字符串实际上就是字符的数组,所以也支持下标索引
在这里插入图片描述

name = "hello world"
print(name[6])    # 输出:w

注意,下标是从0开始的,并且包括空格和特殊字符

切片

切片是指对操作的对象截取其中一部分的操作
字符串、列表、元祖都支持切片操作

切片的语法: [起始:结束:步长]

注意:选区的区间从起始位开始,到结束位的前一位结束(不包含结束位本身),也就是左闭右开区间,步长表示选取间隔

name = "abcdef"
print(name[0:3])    # 输出abc
print(name[1:3])    # 输出bc
print(name[0:5:2])    # 输出ace
print(name[0:-1:2])    # ace
print(name[5:0:-2])    # fdb

这只是一部分的玩法,我个人认为切片是很有意思的,大家可以多尝试尝试
下面给大家拓展一个面试题

name = "abcdef"
print(name[::-1])

大家可以思考一下会出现什么效果

字符串的常见操作

方法01:find()
方法说明:检测str是否包含在mysty中,如果是返回开始的索引值,否则返回-1
格式:mystr.find(str,start=0,end=len(mystr))

my_str = "hello world hello python"
print(my_str.find("python"))	# 输出18,查找到'p'
my_str = "hello world hello python"
print(my_str.find("bao"))	# 输出-1,因为没有找到

方法02:index()
方法说明:检测str是否包含在mystr中,如果是返回开始的索引值,否则报错
格式:mystr.index(str,start=0,end=len(mystr))

mystr = "hello world hello python"
print(mystr.index("py", 0, 10))		# 会发生异常

特殊说明,index()方法,和find()方法一样,只不过如果str不在mystr中会报一个异常.

方法03:count()
方法说明:返回str在start和end之间,在mystr里面出现的次数
格式:mystr.count(str,start=0,end=len(mystr))

mystr = "hello world hello python"
# 注意,这里双引号中间的是小写的l,而不是1
print(mystr.count("l"))	# 输出:5

方法04:replace()
方法说明:把mystr中的str1替换成str2,如果count指定,则替换不超过count次
格式:mystr.replace(str1,str2,mystr.count(str1))

mystr = "hello world hello python"
print(mystr,replace("hello", "HELLO", 1))	# HELLO world hello python

方法05:split()
方法说明:以str为分隔符切片mystr,如果maxsplit有指定值,则仅分割maxsplit个字符串
格式:mystr.split(str=" ",2)

mystr = "hello world hello python"
print(mystr.split(" "))	# 这里是以空格作为分隔符,没有给定最大分割个数

方法06:capitalize()
方法说明:把字符串的第一个字符大写
格式:mystr.capitalize()

my_str = "hello world hello python"
print(my_str.capitalize())	# 会把第一个字母大写

如果第一个字母为空,则没有办法大写

方法07:title()
方法说明:把字符串的每个单词首字母大写
格式:mystr.title()

my_str = "hello world hello python"
print(my_str.title())
# Hello World Hello Python

方法08:startswith()
方法说明:检查字符串是否以str开头,是则返回True,否则返回False
格式:mystr.startswith(str)

mystr = "hello world hello python"
print(mystr.startswith("hello"))		# True

方法09:endswith()
方法说明:检查字符串是否以obj结束,如果是返回True,否则返回False
格式:my_str.endswith(obj)

my_str = "hello world hello python"
print(my_str.endswith("wor"))		# False
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值