python——字符串&切片

本文介绍了Python字符串的基本操作,包括定义、输出、拼接方法。详细讲解了字符串的大小写转换、格式化、查找字符、编码解码、字符判断等功能,并提供了多个示例。此外,还阐述了Python中的切片操作,说明了切片的规则和在列表、元组中的应用,以及在切片中处理越界情况的规则。
摘要由CSDN通过智能技术生成

字符串对象:

1、字符串定义:
(1) 定义:字符串就是一系列字符,在python中,用引号(单引号,双引号,三引号都可以)括起来的都是字符串。例如:“kaikai” , “hello world” ,“xixi is a girl”
(2)输出字符串
直接在print函数中输出字符串。如:print(“kaikai”)
(3)拼接字符串python中使用加号(+)来拼接字符串。如:
在这里插入图片描述
2.字符串的常见方法:
(1)字符串大小写转换
lower() upper() title() capitalize()
== 这4个函数都是改变返回值,不改变原值。==

在控制台演示如下:

 >>> s="the rain stopped and the sky cleared up"
>>> s.upper() #把字符串中小写字符变成大写字符
'THE RAIN STOPPED AND THE SKY CLEARED UP'
>>> s
'the rain stopped and the sky cleared up'
>>> s.lower()  # 把字符串中大写字符变成小写字符
'the rain stopped and the sky cleared up'
>>> s
'the rain stopped and the sky cleared up'
>>> s.title() #将字符串转换为标题格式
'The Rain Stopped And The Sky Cleared Up'
>>> s
'the rain stopped and the sky cleared up'
>>> s.capitalize()
# 让字符串首字母大写(规范化每段的第一句话)
'The rain stopped and the sky cleared up'
>>>

(2)字符串格式(居中or左右对齐)

center(width,[fillchar]) # 设置字符串安装长度居中,fillchar默认是空格,可以自定义
ljust # 左对齐,fillchar默认是空格,可以自定义
rjust # 右对齐,fillchar默认是空格,可以自定义
count() # 统计字符或者字符串出现的次数
endswith() # 判断字符串是否以xxx结尾
startswith() # 判断字符串是否以xxx开头
example:

>>> s.center(50)
'     the rain stopped and the sky cleared up      '
>>> s.center(50,"+")
'+++++the rain stopped and the sky cleared up++++++'
>>> s.ljust(50)
'the rain stopped and the sky cleared up           '
>>> s.rjust(50)
'           the rain stopped and the sky cleared up'
>>> s.count("a")
3
>>> s.endswith("u")
False
>>> s.endswith("p")
True

(3)查找字符
index # 查找字符或者字符串在字符串中第一次出现的位置;如果字符或者字符串不存在,则抛出异常
rindex # 查找字符或者字符串在字符串中最后一次出现的位置
find # 查找字符或者字符串在字符串中第一次出现的位置,如果字符或者字符串不存在,则返回-1
rfind # 查找字符或者字符串在字符串中最后一次出现的位置

>>> s
'the rain stopped and the sky cleared up'
>>> s.index("a")
5
>>> s.rindex("a")
32
></
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值