【python】字符串、转义字符、字符串常用方法

1.字符串

字符串用单引号或双引号包围起来,三个双引号或三个单引号开头的字符串可以换行。

s1 = 'hello,world'
s2 = "hello,world"
s3 = '''hello,
money,
rice'''
s3 = """hello,
world"""

2.转义字符

在字符串中使用\表示转义。
\n表示换行
\t表示制表符
\'表示'
\\表示\

s1 = '\'hello,world!\''
s2 = '\n\\hello,world!\\\n'
print(s1,s2,end='')

输出结果
image

如果不想反斜杠\表示转义,则在字符串前加上字母r

s1 = r'\'hello,world!\''
s2 = r'\n\\hello,world!\\\n'
print(s1,s2,end='') #\'hello,world!\' \n\\hello,world!\\\n

3.使用进制表示字符

\后面跟八进制、十六进制、Unicode编码用来表示字符

s1 = '\141\142\143\x61\x62\x63'
s2 = '\u535a\u5ba2\u56ed'
print(s1,s2) #abcabc 博客园

4.字符串的运算符

运算符 描述
+ 字符串拼接
* 字符串重复
in、not in 判断字符串是否包含另一个字符串
[ ]、[:] 从字符串中取出某个字符或某些字符
s1 = 'hello ' * 3
print(s1) # hello hello hello
s2 = 'world'
s1 += s2
print(s1) # hello hello hello world
print('ll' in s1) # True
print('good' in s1) # False
str2 = 'abc123456'
print(str2[2]) # c,索引从1开始
print(str2[2:5]) # c12,左闭右开
print(str2[2:]) # c123456,开始到结束
print(str2[2::2]) # c246,从2开始,步长为2,取到最后
print(str2[::2]) # ac246,从0开始,步长为2,取到最后
print(str2[::-1]) # 654321cba,步长为-1(把字符串想象成一个圆)
print(str2[-3:-1]) # 45,左闭右开

字符串索引
image

5.字符串常用方法

方法 描述
len() 字符串长度
capitalize() 返回字符串首字母大写
title() 返回字符串每个单词首字母大写
upper() 返回字符串所有字母大写
find('or') 返回字符串中子串的索引,找不到返回-1
index('or') 返回字符串中子串的索引,找不到引发异常
startswith('He') 判断字符串是否以指定字符串开头
endswith('!') 判断字符串是否以指定字符串结尾
center(50,'*') 将字符串以指定宽度居中,并在左右两侧填充指定的字符
rjust(50,' ') 将字符串以指定宽度靠右放置,左侧填充指定字符
isdigit() 判断字符串是否由数字构成
isalpha() 判断字符串是否以字母构成
isalnum() 判断字符串是否以数字和字母构成
strip() 返回去除左右两边空格的字符串
str1 = 'hello,world!'
print(len(str1)) #12
print(str1.capitalize()) #Hello,world!
print(str1.title()) #Hello,World!
print(str1.upper()) #HELLO,WORLD!
print(str1.find('or')) #7
print(str1.find('rice')) #-1
print(str1.index('or')) #7
# print(str1.index('rice')) #报异常
print(str1.startswith('He')) #False
print(str1.startswith('hel')) #True
print(str1.endswith('!')) #True
print(str1.center(50,'*')) #*******************hello,world!*******************,50个字符长度,放中间,两边填充*
print(str1.rjust(50,' ')) # hello,world!
str2 = 'abc123456'
print(str2.isdigit()) #False
print(str2.isalpha()) #False
print(str2.isalnum()) #True
str3 = ' zhangsan@163.com '
print(str3) # zhangsan@163.com
print(str3.strip()) #zhangsan@163.com

6.格式化输出字符串

(1)使用%d

a, b = 5, 10
print('%d*%d = %d' % (a, b, a * b))

(2)使用字符串方法format()

a, b = 5, 10
print('{0}*{1}={2}'.format(a, b, a * b))

(3)在字符串前加上字母f

a, b = 5, 10
print(f'{a}*{b} = {a * b}')
posted @   植树chen  阅读(435)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示