字符串的创建

字符串就是一系列字符,是 Python 中最常用的数据类型。在Python中,用引号括起的都是字符串,其中的引号可以是单引号(‘’),也可以是双引号(“”),如下所示:

# 字符串的创建

str1 = 'Hello World!' # 单引号创建字符串
str2 = "python" # 双引号创建字符串

# 字符串的创建

str1 = 'Hello World!' # 单引号创建字符串
str2 = "python" # 双引号创建字符串

访问字符串中的值

Python 不支持单字符类型,单字符在 Python 中也是作为一个字符串使用。Python访问子字符串,可以使用方括号来截取字符串。

# 访问字符串中的值

print('str1[0]: ', str1[0]) # 索引访问字符串中的值
print('str2[1:5]: ', str2[1:5]) # 切片访问字符串中的值

# 访问字符串中的值

print('str1[0]: ', str1[0]) # 索引访问字符串中的值
print('str2[1:5]: ', str2[1:5]) # 切片访问字符串中的值
# 输出结果
str1[0]: H
str2[1:5]: ytho

# 输出结果
str1[0]: H
str2[1:5]: ytho

三引号的使用

Python三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符。

# 三引号多行字符串

zen_of_python = """
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
print(zen_of_python)

# 三引号多行字符串

zen_of_python = """
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
print(zen_of_python)
# 输出结果

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

# 输出结果

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

转义字符

在需要在字符中使用特殊字符时,Python用反斜杠(\)转义字符。

转义字符

描述

\

用在行尾时,为续行符

\\

反斜杠符号

\'

单引号

\"

双引号

\a

响铃

\b

退格(Backspace)

\000


\n

换行

\v

纵向制表符

\t

横向制表符

\r

回车

\f

换页

\o

八进制数

\x

十六进制数

\other

其它的字符以普通格式输出

字符串的运算符

字符串的运算符总结如下表:

操作符

描述

+

字符串连接

*

重复输出字符串

[]

通过索引获取字符串中字符

[:]

切片截取字符串中的一部分,遵循左闭右开原则

in

成员运算符 ,如果字符串中包含给定的字符返回 True

not in

成员运算符 -,如果字符串中不包含给定的字符返回 True

r,R

无转义输出字符串,所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符

%

格式字符串

# 字符串的运算符

a = "Hello"
b = "Python"

print("a + b 输出结果:", a + b)
print("a * 2 输出结果:", a * 2)
print("a[1] 输出结果:", a[1])
print("a[1:4] 输出结果:", a[1:4])

if "H" in a:
    print("H 在变量 a 中")
else:
    print("H 不在变量 a 中")

if "M" not in b:
    print("M 不在变量 b 中")
else:
    print("M 在变量 b 中")

print(r'\n')
print(R'\n')

# 字符串的运算符

a = "Hello"
b = "Python"

print("a + b 输出结果:", a + b)
print("a * 2 输出结果:", a * 2)
print("a[1] 输出结果:", a[1])
print("a[1:4] 输出结果:", a[1:4])

if "H" in a:
    print("H 在变量 a 中")
else:
    print("H 不在变量 a 中")

if "M" not in b:
    print("M 不在变量 b 中")
else:
    print("M 在变量 b 中")

print(r'\n')
print(R'\n')
# 输出结果

a + b 输出结果:HelloPython
a * 2 输出结果:HelloHello
a[1] 输出结果:e
a[1:4] 输出结果:ell
H 在变量 a 中
M 不在变量 a 中
\n
\n

# 输出结果

a + b 输出结果:HelloPython
a * 2 输出结果:HelloHello
a[1] 输出结果:e
a[1:4] 输出结果:ell
H 在变量 a 中
M 不在变量 a 中
\n
\n

字符串格式化输出

Python支持格式化字符串的输出 。尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符%s的字符串中。

  • %格式化输出

符号

描述

%s

占位符 str()

%d

十进制整数

%x

十六进制

%f

浮点型,默认是输出6位有效数据, 会进行四舍五入

%5d

右对齐,不足左边补空格

%-5d

- 代表左对齐,不足右边默认补空格

%05d

右对齐,不足左边补0

%.2f

保留小数点后2位,指定小数点位数的输出

%4.8f

4代表整个浮点数的长度,包括小数,只有当字符串的长度大于4位才起作用,不足4位空格补足,可以用%04.8使用0补足空格

# 使用 % 格式化输出
name = 'python'
print('Hello %s' % name)

# 使用 % 格式化输出
name = 'python'
print('Hello %s' % name)

python字符串格式化符号:

符  号

描述

%c

格式化字符及其ASCII码

%s

格式化字符串

%d

格式化整数

%u

格式化无符号整型

%o

格式化无符号八进制数

%x

格式化无符号十六进制数

%X

格式化无符号十六进制数(大写)

%f

格式化浮点数字,可指定小数点后的精度

%e

用科学计数法格式化浮点数

%E

作用同%e,用科学计数法格式化浮点数

%g

%f和%e的简写

%G

%f 和 %E 的简写

%p

用十六进制数格式化变量的地址

格式化操作符辅助指令:

符号

功能

*

定义宽度或者小数点精度

-

用做左对齐

+

在正数前面显示加号( + )

在正数前面显示空格

#

在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X')

0

显示的数字前面填充'0'而不是默认的空格

%

'%%'输出一个单一的'%'

(var)

映射变量(字典参数)

m.n.

m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)

  • format格式化输出

(1)format参数调用

  • 按位置调用参数
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1以上版本
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # 用*解压参数
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # 单一位置参数可重复调用
'abracadabra'

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1以上版本
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # 用*解压参数
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # 单一位置参数可重复调用
'abracadabra'
  • 按名称调用参数
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
  • 按方法调用参数
>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
...  'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
...     def __init__(self, x, y):
...         self.x, self.y = x, y
...     def __str__(self):
...         return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'

>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
...  'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
...     def __init__(self, x, y):
...         self.x, self.y = x, y
...     def __str__(self):
...         return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'
  • 按索引调用参数
>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'
>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'

(2)format格式调整

  • 填充\对齐
>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')  # 用'*'来填充
'***********centered***********'

>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')  # 用'*'来填充
'***********centered***********'
  • 正负号对齐\显示
>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # 全显示
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14)  # 将+号用空格填充
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # 只显示负号, 与'{:f}; {:f}'相同
'3.140000; -3.140000'

>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # 全显示
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14)  # 将+号用空格填充
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # 只显示负号, 与'{:f}; {:f}'相同
'3.140000; -3.140000'
  • 数字进制调整
>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
  • 千位分隔符
>>> '{:,}'.format(1234567890)
'1,234,567,890'

>>> '{:,}'.format(1234567890)
'1,234,567,890'
  • 浮点数精度
>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'

>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'
  • 日期格式化输出
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'

>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'
  • 按位置调用参数
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1以上版本
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # 用*解压参数
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # 单一位置参数可重复调用
'abracadabra'

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1以上版本
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # 用*解压参数
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # 单一位置参数可重复调用
'abracadabra'
  • 按名称调用参数
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
  • 按方法调用参数
>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
...  'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
...     def __init__(self, x, y):
...         self.x, self.y = x, y
...     def __str__(self):
...         return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'

>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
...  'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
...     def __init__(self, x, y):
...         self.x, self.y = x, y
...     def __str__(self):
...         return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'
  • 按索引调用参数
>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'

>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'
  • f-string 格式化输出
    f-stringpython3.6之后版本添加的,称之为字面量格式化字符串,是新的格式化字符串的语法。
    f-string格式化字符串以f开头,后面跟着字符串,字符串中的表达式用大括号{}包起来,它会将变量或表达式计算后的值替换进去,实例如下:
# 使用 f-string 格式化输出

name = 'python'
print(f'Hello {name}') # 替换变量
print(f'{1+2}') # 使用表达式

info = {'name':'python', 'url':'www.python.org'}
print(f'{info["name"]}:{info["url"]}')
# 输出结果

Hello python
3
python:www.python.org

用了这种方式明显更简单了,不用再去判断使用 %s,还是 %d

Python 3.8的版本中可以使用 =符号来拼接运算表达式与结果:

x = 1
print(f'{x+1}') # python 3.6
# python 3.6 输出结果

2
# python 3.6新特性
x = 1
print(f'{x+1=}') # python 3.8
# python 3.8 输出结果

x+1=2

字符串内建函数

  • 大小写转换
    .upper() 将指定字符串全部转换为大写
    .lower() 将指定字符串全部转换为小写
    .title() 将指定字符串中所有单词的首字母大写
    .capitalize() 将指定的字符串中首字母大写
    .swapcase() 将指定字符串中的所有大写字母改成小写,小写字母改为大写
# 测试数据

s1 = 'aBcde'
print('s1.upper()结果为:', s1.upper())
print('s1.lower()结果为:', s1.lower())

s2 = 'abcde, qweRTY'
s3 = 'abcde qweRTY'
# 以逗号隔开
print('逗号隔开 s2.title()结果为:', s2.title())
print('逗号隔开 s2.capitalize()结果为:', s2.capitalize())
# 以空格号隔开
print('空格号隔开 s3.title()结果为:', s3.title())
print('空格号隔开 s3.capitalize()结果为:', s3.capitalize())

s4 = 'aBcdEFghiJk'
print('s4.swapcase()结果为:', s4.swapcase())
# 输出结果

s1.lower()结果为:abcde
逗号隔开 s2.title()结果为:Abcde, Qwerty
逗号隔开 s2.capitalize()结果为:Abcde, qwerty
空格号隔开 s3.title()结果为:Abcde Qwerty
空格号隔开 s3.capitalize()结果为:Abcde qwerty
s4.swapcase()结果为:AbCDefGHIjK
  • is判断函数.isdecimal() 判断给定字符串是否全为数字.isalpha() 判断给定的字符串是否全为字母.isalnum() 判断给定的字符串是否只含有数字与字母.isupper() 判断给定的字符串是否全为大写.islower() 判断给定的字符串是否全为小写.istitle() 判断给定的字符串是否符合title().isspace() 判断给定的字符串是否为空白符(空格、换行、制表符).isprintable() 判断给定的字符串是否为可打印字符(只有空格可以,换行、制表符都不可以).isidentifier() 判断给定的字符串是否符合命名规则(只能是字母或下划线开头、不能包含除数字、字母和下划线以外的任意字符)
# 测试数据

print('`1234`全是数字为:', "1234".isdecimal())
print('`asdf4`中4是数字不是字母为:', "asdf4".isdigit())
print('`qwe12@`中@既不是数字也不是字母为:', "qwe12@".isalnum())
print('`asdf`全是小写为:', "asdf".islower())
print('`ADS`全是大写为:', "ADS".isupper())
print('`Wshd,qwe`中是否符合title()为:', "Wshd,qwe".istitle())
print(r'`\n`为换行符,是否属于空白符为:', "\n".isspace())
print(r'`\t`为制表符,是否可打印为:', "\t".isprintable())
print('`qe123`是否符合命名规则为:', "qe125".isidentifier())
# 输出结果

`1234`全是数字为: True
`asdf4`中4是数字不是字母为: False
`qwe12@`中@既不是数字也不是字母为: False
`asdf`全是小写为: True
`ADS`全是大写为: True
`Wshd,qwe`中是否符合title()为: False
`\n`为换行符,是否属于空白符为: True
`\t`为制表符,是否可打印为: False
`qe123`是否符合命名规则为: True
  • 字符串填充.center(width,fillchar=' ') 字符串在中间,填充字符串出现在两边.ljust(width,fillchar=' ') 字符串在左边,填充字符串出现在右边.rjust(width,fillchar=' ') 字符串在右边,填充字符串出现在左边.zfill(width) 只需要传入参数width即可,填充物为“0”,采用居右填充的方式。另外一方面该函数会识别字符串的正负,若为+或者-则不变,越过继续填充
# 测试数据

print('`.center()`结果为:', 'python'.center(10, '+'))
print('`.ljust()`结果为:', 'python'.ljust(10, '+'))
print('`.rjust()`结果为:', 'python'.rjust(10, '+'))
print('`.zfill()`结果为:')
# 不加"+""-"纯数字,用填充物"0"将字符串前填充满
print("12345".zfill(10))
# 加"-"纯数字,越过"-"用填充物"0"将字符串前填充满
print("-125".zfill(10))
# 加"+"数字字母组合,越过"+"用填充物"0"将字符串前填充满
print("+qwe125".zfill(10))
# 加其他符号,用填充物"0"将字符串前填充满
print("#qwe12".zfill(10))
# 输出结果

`.center()`结果为: ++python++
`.ljust()`结果为:python++++
`.rjust()`结果为: ++++python
`.zfill()`结果为:
0000012345
-000000125
+000qwe125
0000#qwe12
  • 子字符串搜索.count(sub[, start[, end]]) 主要对指定字符串搜索是否具有给定的子字符串sub,若具有则返回出现次数。startend代表搜索边界,若无写则代表全字符串搜索.startswith(prefix[, start[, end]]) 判断字符串的开头是否为指定的字符串.endswith(suffix[, start[, end]]) 判断字符串的结尾是否为指定的字符串.find(sub[, start[, end]]) 返回第一个子字符串的位置信息,若无则为-1.rfind(sub[, start[, end]]) 返回最右边的第一个子字符串的位置信息,若无则为-1.index(sub[, start[, end]]) 返回第一个子字符串的位置信息,若无则为报错.rindex(sub[, start[, end]]) 返回最右边的第一个子字符串的位置信息,若无则报错
# 测试数据

s = 'qwertasdqwezxcqwe'
# `.count()`函数
print('搜索`qwe`出现的次数为:', s.count("qwe"))
print('从字符串第 2个开始搜索`qwe`出现的次数为:', s.count("qwe", 1))
print('从字符串第 2个开始到第15个截止搜索`qwe`出现的次数为:', s.count("qwe", 1, 14))

# `.startswith()`函数
print('判断字符串开头是否为`qwe`:', s.startswith("qwe"))
print('从字符串第 2个开始判断字符串开头是否为`qwe`:', s.startswith("qwe",1))

# `.endswith()`函数
print('判断字符串结尾是否为`qwe`:', s.endswith("qwe"))

# `.find()`,`.rfind()`,`.index()`,`.rindex()`函数
print('返回第一个`qwe`的位置为:', s.find("qwe"))
print('返回最右边第一个`qwe`的位置为:', s.rfind("qwe"))
print('返回第一个`qwe`的位置为:', s.index("qwe"))
print('返回最右边第一个`qwe`的位置为:', s.rindex("qwe"))
# 输出结果

搜索`qwe`出现的次数为: 3
从字符串第 2个开始搜索`qwe`出现的次数为: 2
从字符串第 2个开始到第15个截止搜索`qwe`出现的次数为: 1
判断字符串开头是否为`qwe`: True
从字符串第 2个开始判断字符串开头是否为`qwe`: False
判断字符串结尾是否为`qwe`: True
返回第一个`qwe`的位置为: 0
返回最右边第一个`qwe`的位置为: 14
返回第一个`qwe`的位置为: 0
返回最右边第一个`qwe`的位置为: 14
  • 字符串替换.replace(old, new[, count]) 将搜索到的字符串改为新字符串,作为替代函数,旧的字符串与新的字符串是必须输入的count是可选择输入的参数,代表更改个数。.expandtabs(N)\t改为一定数量的空格。空格计算方式:N-(之前字符串长度)=空格数,若N-(之前字符串长度)=0 则空格数为N,若N-(之前字符串长度)<0 则空格数为1。
# 测试数据

s = "qweraqwesfgzqweop"
# `.replace()`函数
print('将字符串全部的`qwe`换为`asd`为:', s.replace("qwe", "asd"))
print('将字符串前两个`qwe`换为`asd`为:', s.replace("qwe", "asd", 2))

# `.expandtabs()`函数
t = "qwe\tqwer\tqasdsdf\tas"
print(r'修改`\t`为一定数量的空格后:', t.expandtabs(4))
# 输出结果

将字符串全部的`qwe`换为`asd`为:asdraasdsfgzasdop
将字符串前两个`qwe`换为`asd`为:asdraasdsfgzqweop
修改`\t`为一定数量的空格后:qwe qwer    qasdsdf as
  • 字符串分割.partition()从左开始,对给定字符串进行切割,切割成三部分,只切割一次。.rpartition() 从右开始,对给定字符串进行切割,切割成三部分,只切割一次。.split(sep=None, maxsplit=-1) 从左开始,对给定的字符串进行切割。.rsplit(sep=None, maxsplit=-1) 从右开始,对给定的字符串进行切割。
# 测试数据

s = "qweraqwesfgzqweop"
# `.partition()`函数
print('`s.partition()`结果为:', s.partition('qwe'))

# `.rpartition()`函数
print('`s.rpartition()`结果为:', s.rpartition('qwe'))

# `.split()`函数
print('`s.split()`结果为:', s.split('qwe'))

# `.rsplit()`函数
print('`s.rsplit()`结果为:', s.rsplit('qwe'))
# 输出结果

`s.partition()`结果为: ('', 'qwe', 'raqwesfgzqweop')
`s.rpartition()`结果为: ('qweraqwesfgz', 'qwe', 'op')
`s.split()`结果为: ['', 'ra', 'sfgz', 'op']
`s.rsplit()`结果为: ['', 'ra', 'sfgz', 'op']
  • 集合类型拼接成字符串
    .join() 将可迭代数据用字符串连接起来,每个参与迭代的元素必须是字符串类型,不能包含数字或其他类型。
# 测试数据

# `.join()`函数
s = "qweraqwesfgzqweop"
print('字符串拼接结果为:', "_".join(s))

tup = ('a', 'b', 'c', 'd')
print('元组拼接结果为:', " + ".join(tup))

ls = ['a', 'b', 'c', 'd']
print('列表拼接结果为:', " x ".join(ls))

# 测试数据

# `.join()`函数
s = "qweraqwesfgzqweop"
print('字符串拼接结果为:', "_".join(s))

tup = ('a', 'b', 'c', 'd')
print('元组拼接结果为:', " + ".join(tup))

ls = ['a', 'b', 'c', 'd']
print('列表拼接结果为:', " x ".join(ls))
# 输出结果

字符串拼接结果为:q_w_e_r_a_q_w_e_s_f_g_z_q_w_e_o_p
元组拼接结果为:a + b + c + d
列表拼接结果为:a x b x c x d

# 输出结果

字符串拼接结果为:q_w_e_r_a_q_w_e_s_f_g_z_q_w_e_o_p
元组拼接结果为:a + b + c + d
列表拼接结果为:a x b x c x d
  • 字符串修剪.strip([chars]) 移除字符串左边和右边的空格或指定字符,如果没传入参数则为移除空格、制表符、换行符.lstrip([chars]) 移除字符串右边的空格或指定字符.rstrip([chars]) 移除字符串左边的空格或指定字符
# 测试数据

s = "qweasdzxcrtqwe---qwe"
# `.strip()`函数
print('移除字符串左边和右边的`qwe`结果为:', s.strip('qwe'))

# `.lstrip()`函数
print('移除字符串左边的`qwe`结果为:', s.lstrip('qwe'))

# `.rstrip()`函数
print('移除字符串右边的`qwe`结果为:', s.rstrip('qwe'))
# 输出结果

移除字符串左边和右边的`qwe`结果为:asdzxcrtqwe---
移除字符串左边的`qwe`结果为:asdzxcrtqwe---qwe
移除字符串右边的`qwe`结果为:qweasdzxcrtqwe---
  • Python 的字符串常用内建函数总结如下:

序号

方法

描述

1

.capitalize()

将字符串的第一个字符转换为大写

2

.center(width, fillchar)

返回一个指定的宽度width 居中的字符串,fillchar 为填充的字符,默认为空格。

3

.count(sub[, start[, end]])

返回字符串中指定字符串出现的次数

4

.decode(encoding="utf-8", errors="strict")

解码为指定的编码格式的字符串

5

.encode(encoding='utf-8',errors='strict')

以 指定的编码格式编码字符串

6

.endswith(suffix[, start[, end]])

判断字符串的结尾是否为指定的字符串,如果是,返回 True,否则返回  False

7

.expandtabs(tabsize=8)

将字符串中的 \t符号转为空格,\t 符号默认的空格数是 8

8

.find(sub[, start[, end]])

检测 sub字符串 是否包含在字符串中,如果指定范围 startend ,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1

9

.index(sub[, start[, end]])

find()方法一样,只不过如果sub字符串不在指定字符串中会报一个异常。

10

.isalnum()

如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False

11

.isalpha()

如果字符串至少有一个字符并且所有字符都是字母或中文字则返回  True, 否则返回 False

12

.isdigit()

如果字符串只包含数字则返回 True,  否则返回 False

13

.islower()

如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回  True,否则返回 False

14

.isnumeric()

如果字符串中只包含数字字符,则返回  True,否则返回 False

15

.isspace()

如果字符串中只包含空白,则返回  True,否则返回 False

16

.istitle()

如果字符串是标题化的(见  title()),则返回 True,否则返回 False

17

.isupper()

如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回  True,否则返回 False

18

.join()

以指定字符串作为分隔符,将 集合中所有的元素合并为一个新的字符串

19

.ljust(width[, fillchar])

返回一个原字符串左对齐,并使用  fillchar 填充至长度width的新字符串,fillchar 默认为空格

20

.lower()

转换字符串中所有大写字符为小写

21

.lstrip()

截掉字符串左边的空格或指定字符

22

.maketrans()

创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标

23

max(str)

返回字符串中最大的字母

24

min(str)

返回字符串中最小的字母

25

len(str)

返回字符串长度

26

.replace(old, new[, count])

将搜索到的字符串改为新字符串,作为替代函数,旧的字符串与新的字符串是必须输入的count是可选择输入的参数,代表更改个数

27

.rfind(sub[, start[, end]])

类似于 find()函数,不过是从右边开始查找

28

.rindex(sub[, start[, end]])

类似于 index(),不过是从右边开始

29

.rjust(width,[, fillchar])

返回一个原字符串右对齐,并使用fillchar(默认空格,填充至长度  width的新字符串

30

.rstrip()

删除字符串字符串末尾的空格

31

.split(sep=None, maxsplit=-1)

从左开始,对给定的字符串进行切割

32

.splitlines([keepends])

按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keependsFalse,不包含换行符,如果为 True,则保留换行符

33

.startswith(prefix[, start[, end]])

判断字符串的开头是否为指定的字符串

34

.strip([chars])

移除字符串左边和右边的空格或指定字符,如果没传入参数则为移除空格、制表符、换行符

35

.swapcase()

将字符串中大写转换为小写,小写转换为大写

36

.title()

返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写

37

.translate(table, deletechars="")

根据给出的表(包含 256  个字符)转换 字符串 的字符,要过滤掉的字符放到 deletechars 参数中

38

.upper()

转换字符串中的小写字母为大写

39

.zfill (width)

返回长度为 width 的字符串,原字符串右对齐,前面填充0

40

.isdecimal()

检查字符串是否只包含十进制字符,如果是返回  True,否则返回 False

参考文档

  1. https://docs.python.org/3/library/string.html#formatstrings
  2. https://www.runoob.com/python3/python3-string.html