Python字符串知识点总结

本文详细介绍了Python字符串的创建、转义字符与原始字符、字符串判断、查询字符、处理字符及格式化字符串的方法,包括字符串的连接、索引、切片、大小写转换、编码、替换等操作,并提供了丰富的示例。

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

文章目录


字符串(string)

Python字符串是一个不可变的 unicode 字符序列,是Python的基本数据类型之一。


提示:以下是本篇文章正文内容,由小编进行网络整理,版权归原作者所有,如有侵权,请联系本人,本人会第一时间删除处理!

一、字符串的创建

1.1 由单引号、双引号、三对单引号或双引号组成。

'''
单引号 '...'
双引号 "..."
三引号 ''' '''、”“” “”“
'''

示例:

str1 = 'spam eggs'
str2 = "spam eggs"
str3 = '''First line.
Second line.'''
str4 = """First line.
Second line"""
  • 单引号与双引号的同时使用情况:
str5 = '"Yes," they said.'
str6 = "doesn't"

1.2 使用 str() 内置函数来定义字符串或将另一种数据类型转换为字符串

# 字符串
greeting = str('hello world!')
print(greeting) # hello world!

# 浮点型
n = 25.95236
str1 = str(n)
print(str1) # 25.95236

# 列表
s = str([1,2,3,4,(5,6,7),{
   8,9,0}])
print(s) # [1, 2, 3, 4, (5, 6, 7), {8, 9, 0}]
print(type(s)) # <class 'str'>

# 元组
s1 = str((1,2,3))
print(s1) # (1, 2, 3)
print(type(s1)) # <class 'str'>

# 字典
s1 = str({
   'a':1,'b':2})
print(s1) # {'a': 1, 'b': 2}
print(type(s1)) # <class 'str'>

# 集合
s1 = str({
   'a','b','c','d'})
print(s1) # {'d', 'b', 'a', 'c'}
print(type(s1)) # <class 'str'>

二、转义字符和原始字符

2.1 常用转义字符

转义字符 说明
\\ (在行尾时) 续行符
\r 回车符,将光标位置移到本行开头。
\t 水平制表符,也即 Tab 键,一般相当于四个空格。
\\ 反斜杠符号
\’ 单引号
\" 双引号
\f 换页

未使用转义字符:
注意:字符串中,遇反斜杠转义字符

print('C:\some\name')  # C:\some
                       # ame

使用转义字符:

print('c:\\some\\name') # c:\some\name

以下这种情况遇到反斜杠不会被转义:

# 注意:最开始的换行没有包括进来
print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

"""
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
"""

2.2 原始字符

字符串一但遇到反斜杠会转义字符,取消转义字符就在字符前面加’r’。

print(r'C:\some\name') # C:\some\name

三、判断字符串

3.1 判断字符串的前缀与后缀

startswith():判断前缀
endswith():判断后缀
前缀:raw_str.startswith(sub_str)
raw_str = "The official home of the Python Programming Language"
star_bool = raw_str.startswith('The')
print(star_bool) # True
后缀:raw_str.endswith(sub_str)
raw_str = "The official home of the Python Programming Language"
end_bool = raw_str.endswith('age')
print(end_bool) # True

3.2 判断子串是否在字符串中

in、not in
in:判断子串在字符串,返回True,否则返回Falsenot in:判断子串不在字符串,返回True,否则返回False

示例:

s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
print('q' in s) # True
print('t' not in s) # False

3.3 判断字符串的类型

A 常用类型:

"""
str.isalnum() # 检测字符串是否是字母、数字组成
str.isalpha() # 检测字符串是否只由字母组成
str.isdigit() # # 检测字符串是否只由数字组成
str.isupper() # 检测字符串中所有的字母是否都为大写
str.islower() # 检测字符串是否由小写字母组成
str.istitle() # 检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写
str.isspace() # 检测字符串是否只由空格组成
"""
A.1 字母、数字组成:isalnum
print('res323'.isalnum()) # True
print('res'.isalnum()) # True
print('1234'.isalnum()) # True
print('res123%$'.isalnum()) # False
A.2 字母组成:isalpha
print('helloworld'.isalpha()) # True 检测字符串是否只由字母组成
print('432323423'.isalpha()) # False
print('while322'.isalpha()) # False
A.3 数字组成:isdigit
print('4253255'.isdigit()) # True
A.4 所有字母都是大写:isupper
res = 'The official home of the Python Programming Language'
print(res.isupper()) # False
print("UPPER".isupper()) # True
A.5 所有字母都是小写:islower
res = 'The official home of the Python Programming Language'
print(res.islower()) # False
print("lower".islower()) # True
A.6 是标题:istitle
res = 'The official home of the Python Programming Language'
print(res.istitle()) # False
print("Hello World".istitle()) # True
A.7 是空格:isspace
res = 'The official home of the Python Programming Language'
print(res.isspace()) # False
print(' '.isspace()) # True
A.8 综合运用例子
sentence = "There are 22 apples"

alphas = 0
digits = 0
spaces = 0

for i in sentence:

    if i.isalpha():
        alphas += 1

    if i.isdigit():
        digits += 1

    if i.isspace():
        spaces += 1

print("一共有", len(sentence), "个字符") # 一共有 19 个字符
print("有", alphas, "个字母") # 有 14 个字母
print("有", digits, "个数字") # 有 2 个数字
print("有", spaces, "个空格") # 有 3 个空格

B 不常用类型

"""
str.isidentifier()
str.isnumeric()
str.isprintable()
str.isdecimal()
str.isascii()
"""
B.1 isidentifier:有效标识符否

由字母、数字、下标线,任意组合为True;不能以数字开头或包含任何空格,其余特殊为False;类似变量的命名规范。

print('1str'.isidentifier()) # False
print('^two'.isidentifier()) # False
print('$two'.isidentifier()) # False

print('one'.isidentifier()) # True
print('_one'.isidentifier()) # True
B.2 isnumeric:只由数字组成,只针对unicode对象
print(u'312321'.isnumeric()) # True
print(u'4324.432'.isnumeric()) # False
print(u'423fv'.isnumeric()) # False
print(u'faads'.isnumeric()) # False
B.3 isdecimal:只包含十进制字符,只针对unicode对象
print(u'42432'.isdecimal()) # True
print(u'42342.424'.isdecimal()) # False
print(u'fasf42324.43'.isdecimal()) # False
print(u'4234.244F'.isdecimal()) # False
B.4 isprintable:所有字符都能打印,就是返回True,有转义字符则为False
print('fsaffaf'.isprintable()) # True
print('if 5>1:print("hell world")'.isprintable()) # True
print('\n\r\nsome\python'.isprintable()) # False
B.5 isascii:检测字符值是否在 7 位 ASCII 集范围内
print('中国'.isascii()) # False
print("123ABC~!@#$%^&*()_\"+{}|:?><;,./".isascii()) # True
print("ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ①②③④⑤⑥⑦⑧⑨⑩一二三四五六七八九十".isascii()) # False
print("ΑΒΓΔΕΖΗΘΙΚ∧ΜΝΞΟ∏Ρ∑ΤΥΦΧΨΩ".isa
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值