首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >「Python」字符串操作

「Python」字符串操作

作者头像
AXYZdong
发布2021-12-07 18:10:30
发布2021-12-07 18:10:30
65100
代码可运行
举报
运行总次数:0
代码可运行

文章目录

在 Python 程序中,如果我们把单个或多个字符用单引号或者双引号包围起来,就可以表示一个字符串。

处理字符串

  • 字符串创建
代码语言:javascript
代码运行次数:0
运行
复制
>>> s1 = 'hello, world!'
>>> s2 = "hello, world!"
>>> s3 = """	
hello, 
world!
"""
>>> print(s1, s2, s3, end='')
hello, world! hello, world! 
hello, 
world!
>>> s4 = """ my     # 以三个双引号或单引号开头的字符串可以换行
name
is
axyzdong
"""
>>> print(s4)
 my
name
is
axyzdong
  • 转义字符

转义字符

打印为

\'

单引号

\''

双引号

\t

制表符

\n

换行符

\\

倒斜杠

  • 原始字符串

可以在字符串开始的引号前加上 r ,使它成为原始字符串。“原始字符串”完全忽略所有的转义字符。

代码语言:javascript
代码运行次数:0
运行
复制
>>> print(r'my name is axyzdong \n')
my name is axyzdong \n
>>> print('my name is \n axyzdong ')
my name is 
 axyzdong
  • 字符串下标和切片
代码语言:javascript
代码运行次数:0
运行
复制
>>> spam = 'Hello world!'
>>> spam[0]
'H'
>>> spam[-1]
'!'
>>> spam[0:1]
'H'
>>> spam[0:2]
'He'
>>> spam[:5]
'Hello'
>>> spam[6:]
'world!'

注:spam[0:1] 中 [0:1]相当于数学中的半开半闭区间 [0,1)

  • in 和 not in
代码语言:javascript
代码运行次数:0
运行
复制
>>> 'Hello' in 'Hello world!'
True
>>> 'hello' in 'Hello world!' #大小写有区别
False
>>> 'world' in 'Hello world!'
True
>>> 'my' in 'Hello world!'
False

常用的字符串方法

代码语言:javascript
代码运行次数:0
运行
复制
>>> spam1 = 'hello world!'
>>> print(len(spam1))	#获取字符串长度
12
>>> print(spam1.capitalize ())	#字符串字母大写拷贝
Hello world!
>>> print(spam1.title ())	#每个单词首字母大写拷贝
Hello World!
>>> print(spam1.upper ())	#字符串变大写后的拷贝
HELLO WORLD!
>>> print(spam1.find ('world'))	#查找字符串所在的位置
6
>>> print(spam1.startswith ('he'))	#检查字符串是否以特定的字符串开头
True
>>> print(spam1.startswith ('He'))
False
>>> print(spam1.endswith ('he'))	#检查字符串是否以特定的字符串结尾
False
>>> print(spam1.endswith ('!'))
True
>>> print(spam1.center (20,'*'))	#将字符串以指定的宽度居中并在两侧填充指定的字符
****hello world!****
>>> print(spam1.rjust (20,' '))	#将字符串以指定的宽度靠右放置左侧填充指定的字符
        hello world!    
>>> spam2 = '123abc'
>>> print(spam2.isdigit ())	#检查字符串是否全由数字构成
False
>>> print(spam2.isalpha ())	#检查字符串是否全由字母构成
False
>>> print(spam2.isalnum ())	#检查字符串是否由数字和字母构成
True
>>> spam3 = '  axyzdong@qq.com   '	#获得字符串左右两侧空格之后的拷贝
>>> print(spam3.strip ())
axyzdong@qq.com
>>> print(spam3)
  axyzdong@qq.com
  • 格式化输出字符串
代码语言:javascript
代码运行次数:0
运行
复制
>>> a, b = 1,2
>>> print('%d + %d = %d'% (a,b,a+b))
1 + 2 = 3
>>> print(f'{a} + {b} = {a+b}')	#Python3.6后简洁的格式化方式
1 + 2 = 3
  • pyperclip 模块拷贝粘贴字符串

pyperclip 模块有copy() 和 paste() 函数,可以向计算机的剪切板发送文本,或从其他接收文本。

代码语言:javascript
代码运行次数:0
运行
复制
>>> import pyperclip
>>> pyperclip.copy ('Hello world!')
>>> pyperclip.paste ()
'pyperclip

参考文献

[1]:https://github.com/jackfrued/Python-100-Days [2]:Python编程快速上手:让繁琐工作自动化/ (美)斯维加特(A1 Sweigart) 著;王海鹏译.北京:人民邮电出版社,2016.7

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/12/05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 处理字符串
  • 常用的字符串方法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档