Python 字符串与布尔值详解

Python 字符串

字符串基础

字符串文字

Python 中的字符串文字可以用单引号或双引号包围,两者效果相同:

python

复制代码
print("Hello")
print('Hello')

字符串赋值

使用变量名、等号和字符串来为变量赋值:

python

复制代码
a = "Hello"
print(a)

多行字符串

使用三个双引号或三个单引号创建多行字符串:

python

复制代码
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

注意: 结果中的换行符位置与代码中的位置一致。

字符串操作

字符串是数组

Python 中的字符串是表示 Unicode 字符的字节数组。单个字符就是长度为 1 的字符串。

访问字符:

python

复制代码
a = "Hello, World!"
print(a[1])  # 输出 'e'(第一个字符位置为 0)

切片操作:

python

复制代码
b = "Hello, World!"
print(b[2:5])  # 输出 'llo'(位置 2 到 5,不包括 5)

负索引切片:

python

复制代码
b = "Hello, World!"
print(b[-5:-2])  # 输出 'orl'(从末尾开始计数)

字符串长度:

python

复制代码
a = "Hello, World!"
print(len(a))  # 输出 13

常用字符串方法

strip() - 删除开头和结尾的空格:

python

复制代码
a = " Hello, World! "
print(a.strip())  # 输出 "Hello, World!"

lower() - 转换为小写:

python

复制代码
a = "Hello, World!"
print(a.lower())  # 输出 "hello, world!"

upper() - 转换为大写:

python

复制代码
a = "Hello, World!"
print(a.upper())  # 输出 "HELLO, WORLD!"

replace() - 替换字符串:

python

复制代码
a = "Hello, World!"
print(a.replace("H", "J"))  # 输出 "Jello, World!"

split() - 分割字符串:

python

复制代码
a = "Hello, World!"
print(a.split(","))  # 输出 ['Hello', ' World!']

字符串检查

使用 innot in 关键字检查字符串内容:

python

复制代码
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)  # 输出 True

y = "ain" not in txt
print(y)  # 输出 False

字符串连接和格式化

字符串连接:

python

复制代码
a = "Hello"
b = "World"
c = a + b
print(c)  # 输出 "HelloWorld"

# 添加空格
c = a + " " + b
print(c)  # 输出 "Hello World"

字符串格式化:

python

复制代码
# 错误示例(不能直接连接字符串和数字)
age = 36
# txt = "My name is John, I am " + age  # 这会报错

# 使用 format() 方法
txt = "My name is John, and I am {}"
print(txt.format(age))

# 多个参数
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

# 使用索引号确保正确位置
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

转义字符

使用反斜杠 \ 插入特殊字符:

python

复制代码
# 错误示例
# txt = "We are the so-called "Vikings" from the north."

# 正确使用转义字符
txt = "We are the so-called \"Vikings\" from the north."
print(txt)

常用转义字符:

  • \' - 单引号

  • \\ - 反斜杠

  • \n - 换行

  • \r - 回车

  • \t - 制表符

  • \b - 退格

  • \f - 换页

  • \ooo - 八进制值

  • \xhh - 十六进制值

字符串方法参考表

方法 描述
capitalize() 将第一个字符转换为大写
casefold() 将字符串转换为小写
center() 返回居中的字符串
count() 返回指定值在字符串中出现的次数
encode() 返回字符串的编码版本
endswith() 如果字符串以指定值结尾,则返回 true
expandtabs() 设置字符串的制表符大小
find() 在字符串中搜索指定的值,并返回找到的位置
format() 格式化字符串中的指定值
format_map() 格式化字符串中的指定值
index() 在字符串中搜索指定的值,并返回找到的位置
isalnum() 如果字符串中的所有字符都是字母数字,则返回 True
isalpha() 如果字符串中的所有字符都是字母,则返回 True
isdecimal() 如果字符串中的所有字符都是十进制数字,则返回 True
isdigit() 如果字符串中的所有字符都是数字,则返回 True
isidentifier() 如果字符串是标识符,则返回 True
islower() 如果字符串中的所有字符都是小写,则返回 True
isnumeric() 如果字符串中的所有字符都是数字,则返回 True
isprintable() 如果字符串中的所有字符都是可打印的,则返回 True
isspace() 如果字符串中的所有字符都是空格,则返回 True
istitle() 如果字符串遵循标题规则,则返回 True
isupper() 如果字符串中的所有字符都是大写,则返回 True
join() 将可迭代的元素连接到字符串的末尾
ljust() 返回字符串的左对齐版本
lower() 将字符串转换为小写
lstrip() 返回字符串的左修剪版本
maketrans() 返回要在翻译中使用的翻译表
partition() 返回一个将字符串分为三部分的元组
replace() 返回替换指定值后的字符串
rfind() 在字符串中搜索指定的值,并返回最后找到的位置
rindex() 在字符串中搜索指定的值,并返回最后找到的位置
rjust() 返回字符串的右对齐版本
rpartition() 返回一个将字符串分为三部分的元组
rsplit() 在指定的分隔符处分割字符串,并返回列表
rstrip() 返回字符串的右修剪版本
split() 在指定的分隔符处分割字符串,并返回列表
splitlines() 在换行符处分割字符串并返回列表
startswith() 如果字符串以指定值开头,则返回 true
strip() 返回字符串的修剪版本
swapcase() 交换大小写
title() 将每个单词的第一个字符转换为大写
translate() 返回翻译后的字符串
upper() 将字符串转换为大写
zfill() 在字符串开头填充指定的 0

注意: 所有字符串方法都返回新值,不会更改原始字符串。

Python 布尔值

布尔值基础

布尔值表示两个值之一:TrueFalse

比较运算:

python

复制代码
print(10 > 9)   # 输出 True
print(10 == 9)  # 输出 False
print(10 < 9)   # 输出 False

条件语句中的布尔值:

python

复制代码
a = 200
b = 33

if b > a:
    print("b is greater than a")
else:
    print("b is not greater than a")  # 输出这句

布尔判断

bool() 函数:

python

复制代码
# 判断字符串和数字
print(bool("Hello"))  # 输出 True
print(bool(15))       # 输出 True

# 判断变量
x = "Hello"
y = 15
print(bool(x))  # 输出 True
print(bool(y))  # 输出 True

值的布尔评估

多数值为 True:

几乎所有有内容的值都会评估为 True

python

复制代码
print(bool("abc"))                          # True
print(bool(123))                           # True
print(bool(["apple", "cherry", "banana"])) # True

一些值为 False:

以下值会评估为 False

python

复制代码
print(bool(False))   # False
print(bool(None))    # False
print(bool(0))       # False
print(bool(""))      # False
print(bool(()))      # False
print(bool([]))      # False
print(bool({}))      # False

自定义类的布尔值:

如果类有返回 0 或 False 的 __len__ 方法,其实例评估为 False

python

复制代码
class myclass():
    def __len__(self):
        return 0

myobj = myclass()
print(bool(myobj))  # 输出 False

函数返回布尔值

函数可以返回布尔值,常用于类型检查等:

python

复制代码
x = 200
print(isinstance(x, int))  # 输出 True

布尔值在条件判断、循环控制和逻辑运算中发挥着重要作用,是 Python 编程的基础组成部分。

相关推荐
鹏多多3 小时前
React项目集成苹果登录react-apple-signin-auth插件手把手指南
前端·javascript·react.js
kennylee263 小时前
WMS系统全景解析:从业务流到系统智能的深度设计
java·交通物流
is08153 小时前
全志 H3 armbian 备份
linux·服务器·网络
往事随风去3 小时前
惊!多线程编程竟成内存杀手:90%程序员不知道的OOM陷阱
java·后端
TZOF3 小时前
TypeScript的新类型(五):tuple元组
前端·后端·typescript
TZOF3 小时前
TypeScript的object大小写的区别
前端·后端·typescript
用户025686170323 小时前
前端面试-leetcode力扣hot100算法题Day1
前端
笔尖的记忆3 小时前
浏览器的观察者
前端·javascript
高热度网3 小时前
初始化electron项目运行后报错 electron uninstall 解决方法
前端·javascript