python3基础之字符串

本文深入讲解Python中的字符串操作,包括字符串的基本概念、切片、拼接、查询与替换等核心功能,并介绍了大小写转换、对齐方式及空格处理等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python基础之字符串

认识字符串

字符串:编程语言中,用于描述数据信息的一段字符。
代码中的字符串:包含在一对引号中的多个字符/三引号中的多个字符。

s1 = "这是一个字符串"
s2 = '这也是一个字符串'
s3 = """
这是一个长字符串
支持换行

在某些情况下,可以当成(文档)注释使用[不赋值]
文件的开头、函数的开头、类型的开头
"""
s4 = "这是一个'特殊'的字符串,单引号和双引号可以交叉使用"
s41 = '单引号字符串中可以"直接包含"双引号'
# 转义:转变原来的含义,符号: \
# \t:将一个普通的字符t,转变成tab制表符
# \n:讲一个普通的字符n,转变成换行符
# \r:将一个普通的字符r,转换成回车符
s5 = "这又是一个\"特殊\"的字符串,双引号中就想用双引号,转义字符"

字符串切片

str = '0123456789'
str[0:3]    #截取第一位到第三位的字符
str[:]       #截取字符串的全部字符
str[6:]     #截取第七个字符到结尾
str[:-3]    #截取从头开始到倒数第三个字符之前
str[2]      #截取第三个字符
str[-1]     #截取倒数第一个字符
str[::-1]   #创造一个与原字符串顺序相反的字符串(字符串反序)
str[-3:-1]  #截取倒数第三位与倒数第一位之间的字符
str[-3:]    #截取倒数第三位到结尾
str[:-5:-3] #逆向截取,倒数第一位与倒数第五位之间的字符,步长为3

===================================
>>> str = '0123456789'
>>> str[0:3]
'012'
>>> str[:]
'0123456789'
>>> str[6:]
'6789'
>>> str[:-3]
'0123456'
>>> str[2]
'2'
>>> str[-1]
'9'
>>> str[::-1]
'9876543210'
>>> str[-3:-1]
'78'
>>> str[-3:]
'789'
>>> str[:-5:-3]
'96'
>>>
>>> str[:-5:-1]
'9876'
>>> str[:-5:1]
'01234'

字符串的拼接

字符串的拼接操作,字符串可以进行运算。

# 1. # 将字符串s重复10次赋值给s1
>>> s = "hello"
>>> s1 = s * 10
>>> print(s1)
hellohellohellohellohellohellohellohellohellohello
>>>
# 2.# 两个字符串可直接通过连接符号+拼接
>>> s2 = "world"
>>> s3 = s1 + s2
>>> s3
'hellohellohellohellohellohellohellohellohellohelloworld'
>>>
# 3. 字符串类型不可以和其他类型直接拼接
# i1 = 10
# s4 = s + i1
# print(s4) # TypeError: must be str, not int
# 4. 字符穿的特殊拼接:占位符拼接
# 字符串占位
>>> name = 'tom'
>>> s5 = "welcome to China, my name is " + name
>>> s6 = "welcome to china, my name is %s" % name
>>> s7 = "hello my name is %s, %s years old!" % (name, 18)
>>>
>>> s5
'welcome to China, my name is tom'
>>> s6
'welcome to china, my name is tom'
>>> s7
'hello my name is tom, 18 years old!'
>>>


# 整数占位
>>> s9 = "this goods%% is ¥%d" % 100
>>> print(s9)
this goods% is100
>>> s9
'this goods% is ¥100'
>>>


# 浮点数占位
s10 = "圆周率是%.10f" % 13.1415926
print(s10)

Python format 格式化函数,Python2.6 开始,新增了一种格式化字符串的函数str.format(),它增强了字符串格式化的功能。基本语法是通过 {} 和 : 来代替以前的 % 。format 函数可以接受不限个参数,位置可以不按顺序。

###字符串字母大小写
capitalize upper lower istitle isupper islower
capitalize首字母大写, upper大写, lower小写,istitle是否首字母大写, isupper是否大写, islower是否小写。

>>> s1 = "Hello"
>>> s2 = "jerry"
>>> s3 = "SHUKE"
>>>
>>> print(s1.capitalize(), s1.upper(), s1.lower())
Hello HELLO hello
>>> print(s1, s1.istitle(), s1.isupper(), s1.islower())
Hello True False False
>>> print(s2, s2.istitle(), s2.isupper(), s2.islower())
jerry False False True
>>> print(s3, s3.istitle(), s3.isupper(), s3.islower())
SHUKE False True False
>>>

###对齐方式
center ljust rjust

S.ljust(width,[fillchar])
#输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格。
S.rjust(width,[fillchar]) #右对齐
S.center(width, [fillchar]) #中间对齐
S.zfill(width) #把S变成width长,并在右对齐,不足部分用0补足

>>> s = "hello"
>>> s.center(10)  # s在操作的时候,占用10个字符,居中对其
'  hello   '
>>> s.center(11, '-') # s在操作的时候,占用11个字符,居中对其,空白的位置使用指定的字符补齐
'---hello---'
>>> s.ljust(10) # s占用10个字符,左对齐
'hello     '
>>> s.rjust(10) # s占用10个字符,右对齐
'     hello'
>>>

###空格处理

  • 剔除空格lstrip rstrip strip
>>> s = "  hello  "
>>> s.lstrip() # 删除字符串s左边的空格
'hello  '
>>> s.rstrip() # 删除字符串s右边的空格
'  hello'
>>> s.strip() # 删除字符串s两边的空格
'hello'
>>>

填充

填充函数-zfill

>>> '1'.zfill(5)
'00001'
>>>

字符串的查询/匹配操作

find(rfind)/index(rindex)/count 查询匹配

>>> s = "hello"
>>> x = s.find("lo") # 查询指定的字符串出现的位置;如果没有查询到返回-1
>>> x2 = s.index("lo")# 查询指定的字符串出现的位置;如果没有查询到直接Error
>>>
>>> x
3
>>> x2
3
>>>

python 字符串对象的find和index方法的区别?
find方法和index方法都是用来查找目标字符串的索引位置,当目标字符串不存在在原字符串中时,find返回-1,表示不存在,而index方法则会抛出异常。

匹配

>>> s = 'hellp'
>>> s.startswith("he") # 判断s是否是"he"开头的字符串吧,返回True/False
True
>>> s.endswith("lo") # 判断s是否是"lo"结尾的字符串,返回True/False
False
>>>

字符串的拆分

split(rsplit) / partition(rpartition) 拆分操作

>>> img = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2913582182,143676263&fm=27&gp=0.jpg"
>>> print(img.rpartition("/")[-1])
u=2913582182,143676263&fm=27&gp=0.jpg
>>> print(img.split("/")[-1])
u=2913582182,143676263&fm=27&gp=0.jpg
>>>

字符串的替换[查询->替换]

简单替换:使用最多的操作方式:replace

S.replace(old, new [, count])

S:表示用户自己定义的一个字符串
old:第一个参数:用来查询的字符串
new:第二个参数:用来替换查询到数据的字符串
count:方括号包含~可选,可以有/没有,表示替换的次数,默认替换所有。
默认情况下全部替换,制定了count~从头开始替换count次

>>> content = "发表一TMD片文章:文TMD章内容中TMD今天真热"
>>> print(content)
发表一TMD片文章:文TMD章内容中TMD今天真热
>>> content = content.replace("TMD", "***")
>>> print(content)
发表一***片文章:文***章内容中***今天真热
>>>

####复杂替换,使用makerans和translate

maketrans(intab, outtab)中两个字符串参数长度必须一样了,因为是字符一对一的映射。

**1) 不添加映射替换 **

>>> s = 'abc123'
>>> table = str.maketrans('', '') # 没有映射,实际上就是按原始字符保留
>>> s.translate(table) # 输出的是原始字符串
'abc123'
>>>
>>> type(str)
<class 'type'>
>>>

**2) 添加映射替换 **

abcde -> bcdef
添加一个映射/对应关系表[a->b b->c c->d]
table = str.maketrans(“abcd”, “bcde”)
完成替换操作
S.translate(table)

**3)添加映射删除替换 **

2.X使用了string的maketrans函数,而3.X使用了str的maketrans函数,除了这一点,使用方法是基本相同的。若指定字符串中要删除的字符时,使用就会略有不同,如下:

2.X下的演示过程:

>>> import string
>>> map = string.maketrans('123', 'abc')
>>> s = '54321123789'
>>> s.translate(map, '78')    #除了转换,还要删除字符串中的字符'7','8'。
'54cbaabc9'               #转换后的字符串没有字符'7','8'。

3.X下的演示过程:

>>> map = str.maketrans('123', 'abc', '47')# 3.x要删除的字符需要在这指定。
>>> s = '123456789abcd'
>>> s.translate(map)
'abc5689abcd'
>>>

3)其它:正则表达式替换…

###其它

  • capitalize/upper/lower/swapcase 大小写转换
  • istitle/islower/isupper 判断大小写
  • isalnum/isdigit/isdecimal/isalpha… 判断组成

字符串函数

字符串函数:python系统内置的对字符串的各种操作的支持
['capitalize', 'casefold',
  'center', 'count', 'encode', 'endswith',
  'expandtabs', 'find', 'format', 'format_map',
  'index', 'isalnum', 'isalpha', 'isdecimal',
  'isdigit', 'isidentifier', 'islower',
  'isnumeric', 'isprintable', 'isspace',
  'istitle', 'isupper', 'join', 'ljust',
  'lower', 'lstrip', 'maketrans', 'partition',
  'replace', 'rfind', 'rindex', 'rjust',
  'rpartition', 'rsplit', 'rstrip', 'split',
  'splitlines', 'startswith', 'strip', 'swapcase',
   'title', 'translate', 'upper', 'zfill']
  • swapcase: 大写变小写,小写变大写。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值