您的位置:  首页 > 技术杂谈 > 正文

盘点Python 中字符串的常用操作

2022-12-27 11:00 https://my.oschina.net/u/4526289/blog/5632451 华为云开发者联盟 次阅读 条评论
摘要:盘点 Python 中字符串的几个常用操作,对新手极度的友好。

本文分享自华为云社区《盘点 Python 中字符串的常用操作,对新手极度友好》,作者:TT-千叶 。

在 Python 中字符串的表达方式有四种

一对单引号
一对双引号
一对三个单引号
一对三个双引号
a = ‘abc’
b= “abc”
c = ‘’‘abc’’’
d = “”“abc”""
print(type(a)) # <class ‘str’>
print(type(b)) # <class ‘str’>
print(type©) # <class ‘str’>
print(type(d)) # <class ‘str’>

单双引号混合使用
a = “LiMing say ‘nice to meet you’”

同样也可以通过转义的方式不用在里面写双引号

a = “LiMing say “nice to meet you””
print(a)

总结就是需要外面用了双引号,里面需要引用的语句可以用单引号括起来,反之亦然。

通常情况根据个人喜好,基本都是使用单引号或者双引号。有些特殊情况,比如需要表示多行时,可以选择三个单(双)引号,并且无序用 \ 进行转移,可直接使用单引号和双引号。

a = ‘’’
My Name is 阿亮,
Let’s say ‘Hello’
‘’’
print(a)

字符串的下标和切换
下标:字符串是一个个字符拼接而成,下标可以理解为每个字符的编号,从 0 开始依次类推。

作用:通过下标去操作字符串中的元素

H的下标为0, e的下标为1 …依次类推

a = ‘HelloWorld’

获取字符串a中下标为4的元素

print(a[4]) # o 下标为4的元素为o

修改字符串中的元素是不是可以直接赋值呢? 例如:

a = ‘HelloWorld’

a[4] = ‘k’
print(a)

上面的代码运行之后发现报错。

TypeError: ‘str’ object does not support item assignment

原因是因为: 字符串一旦创建之后,里面的元素是不可以修改的。

所以字符串是无法直接进行修改的。

字符串运算
字符串运算中用到了 + 、*、>、<、!= 、= 等逻辑运算符。

字符串的相加操作,也可以理解为拼接操作。例如:

a = ‘Hello’ + ’ World’
print(a) # Hello World

也可以写成

a = ‘Hello’ ’ World’
print(a) # Hello World

字符串的乘法操作,可以理解为克隆操作,字符串只能与整数(n)想乘,代表克隆 n 个字符串。

a = ‘a’
print(a * 2) # aa
b = ‘-’
print(b * 10) # ----------

切片
字符串的切片也称为字符串截取。 所有操作都是通过字符串的下标进行操作的。

用法:字符串 [开始索引(start):结束索引(end):步长(step)(默认 1)]

步长(step):每隔(step-1)个取一个元素,当 step 为负数时,代表从右向左取元素,

a = ‘abcdefghijklmn’

从下标1开始 到4结束 进行切片 (包括1,不包括4,即左开又闭)

print(a[1:4]) # bcd
print(a[1:8]) # bcdefgh
print(a[1:8:2])# 步长为2, 结果:bdfh

当补偿为负数时,代表逆向截取。 初始从坐标8开始,每隔一个元素取一个值,到下标为1时结束

print(a[8:1:-2]) # igec

字符串的常用操作
这里以代码 + 注释的方式,展示几个常用的字符串操作。

a = ’ Hello World ’

获取字符串的长度

print(len(a)) # 13

删除字符串两边的空格

print(a.strip()) # Hello World

删除左边的空格

print(a.lstrip()) # Hello World (只删除左边的空格)

删除字符串右边的空格

print(a.rstrip()) # Hello World

通过指定连接符 链接字符串

lst = [‘LiMing’, ‘Tom’]
print(’***’.join(lst)) # LiMing***Tom

首字母大写

m = ‘hello world’
print(m.capitalize()) # Hello world

返回标题化字符串,即每个单词首字母大写

print(m.title()) # Hello World

打印输出字符,将字符串放在中间,

center(width, fillchar) width: 字符串的总长度, fillchar:填充字符

print(a.center(20, ‘*’)) # *** Hello World ****

是否以xxx开头

n = ‘Hello’
print(n.startswith(‘H’)) # True

是否以xxx结尾

print(n.endswith(‘o’)) # True

字符串是全纯英文字符

print(a.isalpha()) # False , 因为字符串a中 ’ Hello World ’ 有空格,因此返回False
print(‘HelloWorld’.isalpha()) #True

判断字符串中是否全部为数字或者英文

print(‘Hello2World’.isalnum()) # True
print(‘123’.isalnum()) # True
print(‘abc&11’.isalnum()) # False

判断是否为整数

print(‘123’.isdigit()) # True
print(‘1.23’.isdigit()) # False

判断字符是否全为小写

print(‘abc’.islower()) # True

判断字符是否全为大写

print(‘Abc’.isupper()) # False
print(‘ABC’.isupper()) # True

字符串小写转大写

print(‘abc’.upper()) # ABC

字符串大写转小写

print(‘ABC’.lower()) # abc

字符串的替换

b = ‘aabbcc’.replace(‘a’, ‘m’)
print(b) # mmbbcc

1 代表替换的个数

b = ‘aabbcc’.replace(‘a’, ‘m’, 1)
print(b) # mabbcc

split 字符串切割,默认空格切割

print(‘aa bb cc’.split()) # [‘aa’, ‘bb’, ‘cc’]
print(‘ab,cd,ef’.split(’,’)) # [‘ab’, ‘cd’, ‘ef’]

字符串换行分割

a = “”"
My Name is ‘762459510,
欢迎添加
“”"
print(a.splitlines()) # [’’, " My Name is ‘762459510’,", ’ 欢迎添加’, ’ ']

字符串的查找
字符串查找常用的方法用 index、find

两者功能相似,区别在于 find 查找不到元素时返回 -1, 不会影响程序运行,而 index 则会抛出异常。

a = ‘abcdef’

查找到元素返回对应的下标

print(a.find(‘c’)) # 2
print(a.find(‘h’)) # -1

print(a.index(‘c’)) # 2
print(a.index(‘h’)) # 抛出异常,ValueError: substring not found

rfind: 类似于 find () 函数,不过是从右边开始查找;返回字符串最后一次出现的位置,如果没有匹配项则返回 - 1 。rindex 同理
a = ‘acmncd’

从右边开始计算,返回第一个匹配到的下标

print(a.rfind(‘c’)) # 4
print(a.rindex(‘c’)) # 4

字符串的格式化
name = ‘762459510’

%s 用于输出字符串

print(‘我的月球号是: %s’ % name)
age = 18

%d 用于输出十进制数字

print(‘我的年龄是:%d’ % age)
money = 1.23

%f 浮点数,默认显示小数点后6位

print(‘我身上有:%f 元’ % money )

指定小数点后的位数

print(‘我身上有:%.2f 元’ % money )

format 操作
除了使用 % 进行格式化,也可以使用 format

print(’{} {}’.format(‘Hello’, ‘World’)) # Hello World
print(’{0} {1}’.format(‘Hello’, ‘World’)) # Hello World

print(’{1}, {0}, {1}’.format(‘A’, ‘B’)) #B, A, B

print(‘今年是 {}年.’.format(2022)) # 今年是 2022年.

 

点击关注,第一时间了解华为云新鲜技术~

展开阅读全文
  • 0
    感动
  • 0
    路过
  • 0
    高兴
  • 0
    难过
  • 0
    搞笑
  • 0
    无聊
  • 0
    愤怒
  • 0
    同情
热度排行
友情链接