Python 教程(三):字符串特性大全

在前两篇教程中,我们学习了 Python 的基本语法和数据结构。本篇教程,我们将深入探讨 Python 中的字符串特性大全

专栏列表


在这里插入图片描述

正文开始如果觉得文章对您有帮助,请帮我三连+订阅,谢谢💖💖💖


前言

Python 3 中的字符串处理功能非常强大,提供了丰富的方法和操作来处理文本数据。下面我们将介绍 字符串的 基本操作、字符串方法、格式化、编码等等功能。

1. 字符串基础

字符串是 Python 中的一种不可变数据类型,用于存储文本数据。

  • 创建字符串:可以使用单引号或双引号来创建字符串。
  • 访问字符:通过索引访问字符串中的字符,索引从 0 开始。
s = "Hello, World!"
print(s[0])  # 输出: H
print(s[7])  # 输出: W

在这里插入图片描述

2. 字符串方法

Python 字符串对象提供了许多有用的方法,用于字符串的查询、修改和处理。

字符串查询

  • str.find(sub):返回子字符串 sub 在字符串中首次出现的索引。
  • str.index(sub):类似于 find(),但如果子字符串不存在则抛出 ValueError
  • str.count(sub):返回子字符串在字符串中出现的次数。
  • str.startswith(prefix):检查字符串是否以指定的前缀开始。
  • str.endswith(suffix):检查字符串是否以指定的后缀结束。

s = "Hello, World!"

print(s.find('o'))
print(s.index('o'))
print(s.count('o'))
print(s.startswith('o'))
print(s.endswith('o'))

在这里插入图片描述

字符串修改

  • str.upper():将字符串中的所有字符转换为大写。
  • str.lower():将字符串中的所有字符转换为小写。
  • str.strip():移除字符串两端的空白字符。
  • str.replace(old, new):替换字符串中的旧子字符串为新子字符串。
s = "Hello, World!"

print(s.upper())
print(s.lower())
print(s.strip())
print(s.replace('o','K'))

在这里插入图片描述

字符串切片

  • str[start:end]:获取字符串从索引 startend-1 的子字符串。
  • str[start:]:获取字符串从索引 start 到末尾的子字符串。
  • str[:end]:获取字符串从开始到索引 end-1 的子字符串。
s = "Hello, World!"

print(s[1:2])
print(s[1:])
print(s[:2])

在这里插入图片描述

3. 字符串格式化

Python 3 提供了多种字符串格式化的方法。

旧式格式化(% 操作符)

name = "张胜男"
age = 30
print("Hello, %s. You are %d years old." % (name, age))
# Hello, 张胜男. You are 30 years old.

str.format() 方法

name = "张胜男"
age = 30
print("Hello, {}. You are {} years old.".format(name, age))

f-string(Python 3.6+)

name = "张胜男"
age = 30
print(f"Hello, {name}. You are {age} years old.")

4. 字符串编码

字符串可以编码为字节序列,反之亦然。

  • str.encode(encoding='utf-8'):将字符串编码为字节序列。
  • bytes.decode(encoding='utf-8'):将字节序列解码为字符串。
s = "Hello, World!"
encoded = s.encode('utf-8')
print(encoded)  # 输出: b'Hello, World!'

decoded = encoded.decode('utf-8')
print(decoded)  # 输出: Hello, World!

5. Unicode 和 ASCII

Python 3 默认使用 Unicode,可以处理多种语言的字符。

  • ord(char):获取单个字符的 Unicode 编码。
  • chr(i):将 Unicode 编码转换为对应的字符。
print(ord('A'))  # 输出: 65
print(chr(65))  # 输出: A

6. 正则表达式

Python 的 re 模块提供了正则表达式的支持,用于复杂的字符串匹配和处理。

import re

pattern = r"\d+"
result = re.findall(pattern, "有123个苹果和456个橙子")
print(result)  # 输出: ['123', '456']

7. 字符串比较

字符串比较是大小写敏感的。

s1 = "hello"
s2 = "Hello"
print(s1 == s2)  # 输出: False

8. 字符串连接

可以使用 + 操作符连接字符串。

s1 = "Hello, "
s2 = "World!"
s3 = s1 + s2
print(s3)  # 输出: Hello, World!

9. 字符串不可变性

字符串是不可变的数据类型,这意味着一旦创建就不能更改。

s = "Hello"
s[0] = "h"  # TypeError: 'str' object does not support item assignment

10. 字符串的内存视图

可以使用 bytesbytearray 来处理二进制数据。

b = bytes([72, 101, 108, 108, 111])  # 等价于 b'Hello'
ba = bytearray(b)
ba[0] = 104  # 修改第一个字符为 'h'
print(ba)  # 输出: bytearray(b'helli')

总结

Python 3 提供了非常丰富的字符串处理功能,从基本的字符串操作到复杂的字符串格式化和正则表达式处理。掌握这些字符串处理技巧可以极大地提高你的编程效率和灵活性。希望这个梳理能帮助你更好地理解和使用 Python 3 的字符串处理功能。如果你有任何问题或需要进一步的帮助,请随时联系我们。

  • 38
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子羽bro

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值