【python基础】06 - python字符串、下标(索引)、切片、String常用方法

一、字符串

1. 字符串的创建

# 单引号
name1 = 'Tom'
# 双引号
name2 = "Rose"
# 三引号
name3 = '''Tom'''
name4 = """Rose"""

注意单双引号和三引号创建字符串的区别:

str1 = ('hello w'
        'orld')
print(str1) # 单引号不支持字符串内换行
str2 = """hello w
orld"""
print(str2) # 三引号支持字符串内换行
'''
hello world
hello w
orld
'''

注意,引号两两匹配

# d = 'I'm Tom' # 这种出现无法匹配的'是不允许的
# 解决方法1:将字符串引号变成双引号
d = "I'm Tom"
# 解决方法2:加反斜杠变转义字符
d = 'I\'m Tom'
print(d)

2. 字符串的输出

① 正常输出 ② 格式化输出

# 正常输出
print('hello')
name = 'Tim'
# 格式化输出
print('我的名字是%s' % name)
print(f'我的名字是{name}')
'''
hello
我的名字是Tim
我的名字是Tim
'''

3. 字符串的输入

python中,使用input()接收用户输入

password = input('请输入您的密码:')
print(f'您输入的密码为{password}')
print(type(password))
# input作为输入,所保存下来的类型必定是字符型
'''
请输入您的密码:123
您输入的密码为123
<class 'str'>
'''

二、下标

  • “下标” = “索引” = “编号”
  • 下标的作用是:通过下标实现快速访问
  • 下标从0开始
  • 下标在字符串、列表、元组中都有涉及
str1 = 'abcdef'
print(str1[0])
print(str1[2])
'''
a
c
'''

三、切片

  • 切片是指对操作对象 截取其中一部分 的操作
  • 字符串、列表、元组都持支持切片操作(有下标就支持)

1. 切片语法

序列[开始位置下标:结束位置下标:步长]

注意事项:

  • 所选取的数据范围:[开始位置下标,结束位置下标)
  • 下标正负均可
  • 步长即为间隔,默认为1,正负均可
  • 选取方向和步长方向一致才能正常提取数据(见下边示例)
str1 = 'abcdefgh'
print(str1[2]) # c
print(type(str1[2])) # <class 'str'>
# 注意切片截出来的无论有几个字符,都仍然是字符串类型

print(str1[2:5:1]) # cde
print(str1[2:5:2]) # ce
print(str1[2:5]) # cde
print(str1[:5]) # abcde即[头, 5)
print(str1[2:]) # cdefgh即[2, 尾]
print(str1[:]) # abcdefgh即[头,尾]

# 步长为附属,表示倒数选取
print(str1[::-1]) # hgfedcba即获取所有,且是倒数关系
# 负数做索引,-1代表倒数第一个位置,-2代表倒数第二个位置
print(str1[-4::-1]) # edcba即-4位置开始,倒着取,取到表头
print(str1[-4:-1:1]) # efg即[-4,-1)

print(str1[-4:-1:-1]) # 无法选出数据:从-4开始到-1结束,选取方向为从左向右, 但是-1步长为从右向左选取
# 注意:如果 选取方向 和 步长方向 相冲突,则无法选取数据!!!
print(str1[-1:-4:-1]) # hgf 这种选法方向一致,可以选择

四、String常用方法

1. 查找

查找子串在字符串中出现的位置或次数

  • find():查找子串是否包含在这个字符串中,如果在,返回这个子串开始的位置下标,否则返回-1
    • 语法:字符串序列.find(子串,开始位置下标,结束位置下标)
    • 开始和结束位置下标可以省略,表示在整个字符串序列中查找
    • 示例:
mystr = 'hello world and hi and this is a new challenge'
# 1. find()
print(mystr.find('and')) # 12(返回的是第一个and出现的位置)
print(mystr.find('and',15, 30)) # 19(在15~30内出现的位置)
print(mystr.find('hhhhh')) # -1(说明该子串hhhhh不在字符串内)
  • index():查找子串是否包含在这个字符串中,如果在,返回这个子串开始的位置下标,否则报错
    • 语法:字符串序列.index(子串,开始位置下标,结束位置下标)
    • 开始和结束位置下标可以省略,表示在整个字符串序列中查找
    • 示例:
mystr = 'hello world and hi and this is a new challenge'
# 2.index()
print(mystr.index('and')) # 12
print(mystr.index('and',15, 30)) # 19
print(mystr.index('hhhhh')) # 会报错(这是区别于find的地方)
  • count():统计子串在字符串中出现的次数,如果子串在字符串中,返回出现次数,否则返回0
    • 语法:字符串序列.count(子串,开始位置下标,结束位置下标)
    • 开始和结束位置下标可以省略,表示在整个字符串序列中查找
    • 示例:
mystr = 'hello world and hi and this is a new challenge'
# 3. count()
print(mystr.count('and')) # 2
print(mystr.count('and', 15,30)) # 1
print(mystr.count('hhhhh')) # 0(说明该子串hhhhh不在字符串内)

补充:

  • rfind():和find()功能相同,但是查找方向是从右侧开始(但下标还是正常的从左往右计算)
  • rindex():和index()功能相同,但查找方向是从右侧开始
mystr = 'hello world and hi and this is a new challenge'
print(mystr.rfind('and')) # 12(返回的是第一个and出现的位置) # 19
# 可以看到,返回的第一个and的位置是从右向左计算而来的

2. 修改

修改字符串指通过某些函数修改字符串中的内容

  • replace():用新子串替换某旧子串
    • 语法:字符串序列.replace(旧子串,新子串,替换次数)
    • 不会修改原字符串,也就是说必须有一个新变量来接收(replace的返回值才是修改后的数据)(也就是说,字符串是不可变数据类型
    • 替换次数为该字串出现的次数,如果替换次数超出子串在字符串中出现的总次数,那么等价于字符串中出现了的全部替换
    • 示例:
mystr = 'hello world and hi and this is a new challenge'

# replace()将and替换成or
new_str = mystr.replace('and', 'or')
print(mystr) # hello world and hi and this is a new challenge 原字符串没有更改
print(new_str) # hello world or hi or this is a new challenge 所有的and都替换成or
new_str1 = mystr.replace('and', 'or',1)
print(new_str1) # hello world or hi and this is a new challenge 只替换了第一个and
new_str2 = mystr.replace('and', 'or',100)
print(new_str2) # hello world or hi and this is a new challenge 出现了的全部替换
  • split():按照指定字符分割字符串
    • 语法:字符串序列.split(分割字符,num)
    • num表示分割字符出现的次数(将来返回的数据个数为num+1个)
    • 返回一个列表
    • 示例:
mystr = 'hello world and hi and this is a new challenge'

# split 用and分割
list1 = mystr.split('and')
print(list1) # ['hello world ', ' hi ', ' this is a new challenge']
list2 = mystr.split('and', 1) # 分割符号只出现一次,返回的列表有两个元素
print(list2) # ['hello world ', ' hi and this is a new challenge']
  • join():用一个字符或子串合并字符串(即将多个字符串合并为一个新的字符串)
    • 语法:字符或子串.join(多字符串组成的序列)
    • 示例:
# join() 合并列表里面的字符串数据为一个大字符串
mylist = ['aa', 'bb', 'cc']
# 想得到aa...bb...cc
list1 = '...'.join(mylist)
print(list1) # aa...bb...cc

补充:

  • capitalize():将字符串的 第一个字符 转换成大写(只有第一个字符大写,其他的反而会变成小写)
  • title():将字符串中 每个单词 的首字母转换成大写
  • lower():字符串中的大写转成小写
  • upper():字符串中的小写转成大写
mystr = 'hello world and hi and this is a new challenge'
# 首字母大写,其他的都变成小写
print(mystr.capitalize()) # Hello world and hi and this is a new challenge
mystr1 = 'hello world and Hi and This is a new Challenge'
print(mystr1.capitalize()) # Hello world and hi and this is a new challenge
# 所有单词首字母大写
print(mystr.title()) # Hello World And Hi And This Is A New Challenge


# 大写转小写
print(mystr1.lower()) # hello world and hi and this is a new challenge
# 小写转大写
print(mystr1.upper()) # HELLO WORLD AND HI AND THIS IS A NEW CHALLENGE
  • lstrip():删除字符串左侧空白
  • rstrip()删除字符串右侧空白
  • srtip()删除字符串两侧空白
mystr = '       hello world and hi and this is a new challenge      '
print(mystr) # ‘       hello world and hi and this is a new challenge      ’
# 删除左侧空白符
print(mystr.lstrip()) # ‘hello world and hi and this is a new challenge      ’
# 删除右侧空白符
print(mystr.rstrip()) # ‘       hello world and hi and this is a new challenge’
# 删除两侧空白符
print(mystr.strip()) # ‘hello world and hi and this is a new challenge’
  • ljust():返回一个原字符串左对齐,并使用指定字符(默认空格)填充至对应长度的新字符串。语法:字符串序列.ljust(长度,填充字符)
  • rjust():返回一个原字符串右对齐,并使用指定字符(默认空格)填充至对应长度的新字符串。语法和ljust()相同。
  • center():返回一个原字符串居中对齐,并使用指定字符(默认空格)填充至对应长度的新字符串。语法和ljust()相同。
mystr = 'hello'
# 字符串左对齐且填充为长度为10的新字符串,默认空格填充
print(mystr.ljust(10)) # ‘hello     ’
# 字符串左对齐且填充为长度为10的新字符串,用*填充
print(mystr.ljust(10, '*')) # 'hello*****'

# 字符串右对齐且填充为长度为10的新字符串,默认空格填充
print(mystr.rjust(10)) # ‘     hello’
# 字符串右对齐且填充为长度为10的新字符串,用*填充
print(mystr.rjust(10, '*')) # '*****hello'

# 字符串居中对齐且填充为长度为10的新字符串,默认空格填充
print(mystr.center(10)) # ‘  hello   ’
# 字符串居中对齐且填充为长度为10的新字符串,用*填充
print(mystr.center(10, '*')) # '**hello***'

3. 判断

判断字符串的内容或性质,返回布尔类型

  • startswith():检查字符串是否以规定子串开头,是则返回True,否则返回False。
    • 语法:字符串序列.startswith(子串,开始位置下标,结束位置下标)
    • 开始和结束位置下标可省略,如果设置了开始和结束位置下标,那么只在指定的范围内检查。
    • 示例:
mystr = 'hello world and hi and this is a new challenge'
print(mystr.startswith('hello')) # True
print(mystr.startswith('hhh')) # False
  • endswith():检查字符串是否以规定子串结尾,是则返回True,否则返回False。
    • 语法:字符串序列.startswith(子串,开始位置下标,结束位置下标)
    • 开始和结束位置下标可省略,如果设置了开始和结束位置下标,那么只在指定的范围内检查。
    • 示例:
mystr = 'hello world and hi and this is a new challenge'
print(mystr.endswith('lenge')) # True
print(mystr.endswith('hhhh')) # False
  • isdigit():检查字符串是否只包含数字,是则返回True,否则返回False。
  • isalpha():检查字符串是否只包含字母,是则返回True,否则返回False。
str1 = 'ababab'
str2 = 'adc32d'
str3 = '324242'
print(str2.isdigit()) # False
print(str3.isdigit()) # True
print(str1.isalpha()) # True
print(str2.isalpha()) # False
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值