python中字符串str的使用

python中str的使用

在 Python 中,str(字符串)是不可变的数据类型,用于存储文本数据。Python 提供了丰富的字符串操作方法,下面是对 str 类型的详细讲解。

1. 创建字符串

Python 中可以使用单引号 '双引号 "三引号 ''' """ 创建字符串:

s1 = 'hello'
s2 = "hello"
s3 = '''hello'''
s4 = """hello"""
print(s1, s2, s3, s4)  # 输出:hello hello hello hello

三引号 主要用于多行字符串:

s = """这是一个
多行字符串"""
print(s)
2. 字符串的基本操作
2.1 拼接 + 和重复 *
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2)  # Hello World
print(s1 * 3)  # HelloHelloHello
2.2 获取字符串长度 len()
s = "Python"
print(len(s))  # 6
2.3 访问字符串中的字符(索引 & 切片)

Python 中字符串支持 索引 (indexing)和 切片 (slicing):

s = "Python"
print(s[0])   # P(索引从 0 开始)
print(s[-1])  # n(倒数第 1 个字符)

切片(截取子串)

print(s[1:4])   # "yth"(索引 1 到 3)
print(s[:4])    # "Pyth"(从头到索引 3)
print(s[2:])    # "thon"(索引 2 到末尾)
print(s[::-1])  # "nohtyP"(反转字符串)
3. 字符串常用方法

Python 提供了丰富的字符串操作方法:

3.1 大小写转换
s = "Python Programming"
print(s.lower())  # python programming
print(s.upper())  # PYTHON PROGRAMMING
print(s.capitalize())  # Python programming
print(s.title())  # Python Programming
3.2 去除空格 strip()
s = "  hello  "
print(s.strip())   # "hello"(去掉前后空格)
print(s.lstrip())  # "hello  "(去掉左侧空格)
print(s.rstrip())  # "  hello"(去掉右侧空格)
3.3 查找和替换
s = "hello world"
print(s.find("world"))  # 6(找到"world"的索引)
print(s.replace("world", "Python"))  # "hello Python"
3.4 字符串分割和连接
s = "apple,banana,orange"
words = s.split(",")  # 按逗号分割成列表
print(words)  # ['apple', 'banana', 'orange']

new_s = "-".join(words)  # 用 "-" 连接列表元素
print(new_s)  # "apple-banana-orange"
4. 格式化字符串

Python 支持多种字符串格式化方法。

4.1 f-string(推荐)
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
4.2 format() 方法
print("My name is {} and I am {} years old.".format(name, age))
4.3 旧式 % 格式化
print("My name is %s and I am %d years old." % (name, age))
5. 字符串的判断方法
s = "hello123"
print(s.isalpha())  # False(包含数字,不是纯字母)
print(s.isdigit())  # False(包含字母,不是纯数字)
print(s.isalnum())  # True(字母+数字)

print("  ".isspace())  # True(纯空格)
print("Python".startswith("Py"))  # True
print("Python".endswith("on"))  # True
6. 字符串的不可变性

Python 的字符串是**不可变(immutable)**的,不能直接修改:

s = "hello"
# s[0] = "H"  # ❌ 会报错
s = "Hello"  # ✅ 只能重新赋值
7. 字符串的编码

Python 默认使用 UTF-8 编码,可以使用 encode()decode() 进行转换:

s = "你好"
encoded_s = s.encode("utf-8")  # 编码为字节
print(encoded_s)  # b'\xe4\xbd\xa0\xe5\xa5\xbd'

decoded_s = encoded_s.decode("utf-8")  # 解码回字符串
print(decoded_s)  # 你好
总结:
  • 字符串是不可变的 ,不能修改其中的字符,只能重新赋值。
  • 支持索引和切片 ,可以提取子串、倒序排列等。
  • 提供丰富的字符串方法 ,如大小写转换、查找、替换、分割、连接等。
  • 支持格式化输出 ,推荐使用 f-string
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

bit_lin

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

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

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

打赏作者

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

抵扣说明:

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

余额充值