Python教程(五):字符串操作 — 从基础到格式化

今天我们将深入探讨Python中最常用的数据类型之一:字符串

无论您是在构建聊天机器人、抓取网站还是处理数据 — 您都会一直使用字符串。所以让我们掌握基础知识,学习如何有效地格式化和操作字符串。


今天您将学习什么

  • 字符串是什么以及如何定义它们
  • 字符串索引和切片
  • 常用的字符串方法
  • 字符串连接和重复
  • 如何清晰地格式化字符串

什么是字符串?

在Python中,字符串是用引号包围的字符序列。

name = "Alice"
greeting = 'Hello, world!'

您可以使用单引号(' ')或双引号(" ")


字符串索引和切片

索引:

字符串中的每个字符都有一个索引号:

word = "Python"
print(word[0])  # P
print(word[5])  # n

Python使用从零开始的索引,所以第一个字符在位置0

切片:

您可以使用切片提取字符串的部分:

print(word[0:3])  # Pyt
print(word[2:])   # thon
print(word[-1])   # n (最后一个字符)

字符串连接和重复

连接:

使用+连接字符串:

first = "Good"
second = "Morning"
print(first + " " + second)  # Good Morning

重复:

使用*重复字符串:

print("Ha" * 3)  # HaHaHa

常用的字符串方法

Python字符串有很多内置方法:

text = "  Hello, Python!  "

print(text.strip())       # 移除空白:Hello, Python!
print(text.lower())       # 转换为小写
print(text.upper())       # 转换为大写
print(text.replace("Python", "World"))  # 替换文本
print(text.find("Python"))  # 查找子字符串索引

一些有用的字符串方法:

方法描述.strip()移除开头/结尾的空白.lower()转换为小写.upper()转换为大写.replace()用一个子字符串替换另一个.find()查找子字符串的第一个索引.split()将字符串分割成列表.join()将列表连接成字符串


字符串格式化

假设您想在句子中包含变量。这里有3种格式化字符串的方法:

1 连接(不理想):

name = "Alice"
print("Hello " + name + "!")

2str.format():

print("Hello, {}!".format(name))

3 f-字符串(Python 3.6+的最佳实践):

print(f"Hello, {name}!")

f-字符串可读性强、速度快,是格式化字符串最现代的方式。

您甚至可以在其中进行表达式:

age = 25
print(f"In 5 years, you'll be {age + 5} years old.")

奖励:多行字符串

使用三引号创建多行字符串:

message = """Hello,
This is a multi-line
string in Python."""
print(message)

回顾

今天您学习了:

  • 如何定义、访问和切片字符串
  • 如何连接和重复字符串
  • 常用的字符串方法
  • 使用f-字符串进行字符串格式化的最佳实践
原文链接:,转发请注明来源!