Python 字符串(str)全方位剖析:从基础入门、方法详解到跨语言对比与知识拓展

Python 字符串(str)全方位剖析:从基础入门、方法详解到跨语言对比与知识拓展

本文将深入探讨 Python 中字符串(str)的相关知识,涵盖字符串的定义、创建、基本操作、格式化等内容。同时,会将 Python 字符串与其他常见编程语言(如 Java、C++)中的字符串进行比较,帮助读者更好地理解不同语言中字符串处理的异同。此外,会对class str进行详细介绍,并对所有字符串方法进行逐一详解,还会对相关知识点进行扩展深化,提供丰富的示例代码和详细的解释,让读者能够全面掌握 Python 字符串的使用。

一、Python 字符串(str)基础

1. 字符串的定义

在 Python 中,字符串是由一系列字符组成的不可变序列,可以使用单引号(')、双引号(")或三引号('''""")来表示。

# 使用单引号
str1 = 'Hello, World!'
# 使用双引号
str2 = "Python is great"
# 使用三引号(可以跨多行)
str3 = '''This is a
multi - line string'''

2. 字符串的创建

除了直接使用引号创建字符串外,还可以使用str()函数将其他数据类型转换为字符串。

num = 123
str_num = str(num)
print(type(str_num))  # <class 'str'>

3. 字符串的基本操作

索引和切片

字符串中的每个字符都有一个索引,索引从 0 开始。可以使用索引来访问单个字符,也可以使用切片来获取子字符串。

s = "Python"
# 访问单个字符
print(s[0])  # P
# 切片操作
print(s[1:3])  # yt
拼接和重复

可以使用+运算符来拼接字符串,使用*运算符来重复字符串。

str_a = "Hello"
str_b = "World"
# 拼接
print(str_a + " " + str_b)  # Hello World
# 重复
print(str_a * 3)  # HelloHelloHello
字符串长度

可以使用len()函数来获取字符串的长度。

s = "Python"
print(len(s))  # 6

4. 字符串的格式化

Python 提供了多种字符串格式化的方法,如旧式的%格式化、str.format()方法和 f - 字符串。

旧式的%格式化
name = "Alice"
age = 25
print("My name is %s and I'm %d years old." % (name, age))
str.format()方法
name = "Bob"
age = 30
print("My name is {} and I'm {} years old.".format(name, age))
f - 字符串(Python 3.6+)
name = "Charlie"
age = 35
print(f"My name is {name} and I'm {age} years old.")

二、class str 介绍

在 Python 中,str是一个内置类,用于表示字符串对象。所有使用引号创建的字符串都是str类的实例。str类提供了许多有用的方法来处理字符串。当我们创建一个字符串时,实际上是在创建一个str类的对象,并且可以调用该对象的各种方法。

s = "example"
print(type(s))  # <class 'str'>

三、Python 字符串(str)方法详解

1. 大小写转换方法

upper()

将字符串中的所有小写字母转换为大写字母。

s = "hello"
print(s.upper())  # HELLO
lower()

将字符串中的所有大写字母转换为小写字母。

s = "WORLD"
print(s.lower())  # world
title()

将字符串中每个单词的首字母转换为大写,其余字母转换为小写。

s = "hello world"
print(s.title())  # Hello World
capitalize()

将字符串的第一个字符转换为大写,其余字符转换为小写。

s = "hello world"
print(s.capitalize())  # Hello world
swapcase()

将字符串中的大写字母转换为小写字母,小写字母转换为大写字母。

s = "HeLlO"
print(s.swapcase())  # hElLo

2. 查找和替换方法

find(sub[, start[, end]])

返回子字符串sub在字符串中第一次出现的索引,如果未找到则返回 -1。startend参数可选,用于指定查找的起始和结束位置。

s = "hello world"
print(s.find("world"))  # 6
rfind(sub[, start[, end]])

find()方法类似,但从字符串的右侧开始查找。

s = "hello world world"
print(s.rfind("world"))  # 12
index(sub[, start[, end]])

find()方法类似,但如果未找到子字符串会抛出ValueError异常。

s = "hello world"
print(s.index("world"))  # 6
rindex(sub[, start[, end]])

rindex()方法类似,但从字符串的右侧开始查找,未找到会抛出ValueError异常。

s = "hello world world"
print(s.rindex("world"))  # 12
replace(old, new[, count])

将字符串中的所有old子字符串替换为new子字符串。count参数可选,用于指定替换的次数。

s = "hello world"
print(s.replace("world", "python"))  # hello python

3. 去除空白字符方法

strip([chars])

去除字符串首尾的指定字符,默认为去除空白字符(空格、制表符、换行符等)。

s = "  hello  "
print(s.strip())  # hello
lstrip([chars])

去除字符串左侧的指定字符,默认为去除空白字符。

s = "  hello  "
print(s.lstrip())  # hello  
rstrip([chars])

去除字符串右侧的指定字符,默认为去除空白字符。

s = "  hello  "
print(s.rstrip())  #   hello

4. 分割和连接方法

split(sep=None, maxsplit=-1)

根据指定的分隔符sep将字符串分割成一个列表。maxsplit参数可选,用于指定最大分割次数。如果sep未指定,则默认以空白字符作为分隔符。

s = "hello world"
print(s.split())  # ['hello', 'world']
rsplit(sep=None, maxsplit=-1)

split()方法类似,但从字符串的右侧开始分割。

s = "hello world"
print(s.rsplit())  # ['hello', 'world']
splitlines([keepends])

根据换行符将字符串分割成一个列表。keepends参数可选,为True时保留换行符,默认为False

s = "hello\nworld"
print(s.splitlines())  # ['hello', 'world']
join(iterable)

将可迭代对象中的元素用指定的字符串连接起来。

lst = ['hello', 'world']
s = " ".join(lst)
print(s)  # hello world

5. 判断方法

startswith(prefix[, start[, end]])

判断字符串是否以指定的前缀prefix开头。startend参数可选,用于指定判断的起始和结束位置。

s = "hello world"
print(s.startswith("hello"))  # True
endswith(suffix[, start[, end]])

判断字符串是否以指定的后缀suffix结尾。startend参数可选,用于指定判断的起始和结束位置。

s = "hello world"
print(s.endswith("world"))  # True
isalpha()

判断字符串是否只由字母组成。

s = "hello"
print(s.isalpha())  # True
isdigit()

判断字符串是否只由数字组成。

s = "123"
print(s.isdigit())  # True
isalnum()

判断字符串是否只由字母和数字组成。

s = "hello123"
print(s.isalnum())  # True
isspace()

判断字符串是否只由空白字符组成。

s = "   "
print(s.isspace())  # True
islower()

判断字符串中的所有字母是否都是小写。

s = "hello"
print(s.islower())  # True
isupper()

判断字符串中的所有字母是否都是大写。

s = "HELLO"
print(s.isupper())  # True
istitle()

判断字符串是否是标题格式(每个单词的首字母大写)。

s = "Hello World"
print(s.istitle())  # True

6. 填充和对齐方法

ljust(width[, fillchar])

返回一个左对齐的字符串,宽度为width,不足的部分用fillchar填充,默认为空格。

s = "hello"
print(s.ljust(10, '*'))  # hello*****
rjust(width[, fillchar])

返回一个右对齐的字符串,宽度为width,不足的部分用fillchar填充,默认为空格。

s = "hello"
print(s.rjust(10, '*'))  # *****hello
center(width[, fillchar])

返回一个居中对齐的字符串,宽度为width,不足的部分用fillchar填充,默认为空格。

s = "hello"
print(s.center(10, '*'))  # **hello***
zfill(width)

返回一个长度为width的字符串,不足的部分在左侧用 0 填充。

s = "123"
print(s.zfill(5))  # 00123

四、Python 字符串与其他语言字符串的比较

1. Python 与 Java 字符串比较

特性PythonJava
定义方式单引号、双引号、三引号双引号
不可变性字符串是不可变的字符串是不可变的(String类),但有可变的StringBuilderStringBuffer
格式化%格式化、str.format()、f - 字符串String.format()方法
拼接+运算符+运算符,也可使用StringBuilderStringBuffer进行高效拼接

2. Python 与 C++ 字符串比较

特性PythonC++
定义方式单引号、双引号、三引号std::string类,使用双引号
不可变性字符串是不可变的std::string是可变的
格式化%格式化、str.format()、f - 字符串std::stringstreamstd::format(C++20 及以上)
拼接+运算符+运算符

五、相关知识点扩展深化

1. 字符串的编码与解码

在 Python 中,可以使用encode()方法将字符串编码为字节序列,使用decode()方法将字节序列解码为字符串。

s = "你好"
# 编码
bytes_s = s.encode('utf - 8')
# 解码
decoded_s = bytes_s.decode('utf - 8')
print(decoded_s)  # 你好

总结

本文详细介绍了 Python 中字符串(str)的定义、创建、基本操作和格式化方法,深入讲解了class str以及所有字符串方法。同时将 Python 字符串与 Java、C++ 中的字符串进行了比较。Python 字符串具有简洁的定义方式和丰富的操作方法,并且提供了多种字符串格式化的手段。在处理字符串时,需要注意字符串的不可变性,以及根据具体需求选择合适的操作方法。此外,还对字符串的编码与解码等相关知识点进行了扩展深化。

TAG:Python、字符串、str、字符串方法、字符串比较、字符串格式化

相关学习资源

  • Python 官方文档 - 字符串操作:https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str 。Python 官方提供的关于字符串操作的详细文档,包含了所有字符串方法的介绍和示例。
  • Java 官方文档 - String 类:https://docs.oracle.com/javase/8/docs/api/java/lang/String.html 。Java 官方关于String类的文档,介绍了 Java 中字符串的各种方法和使用。
  • C++ 参考手册 - std::string:https://en.cppreference.com/w/cpp/string/basic_string 。C++ 参考手册中关于std::string的详细介绍,包含了std::string的各种操作和方法。
  • Tekin的Python编程秘籍库Python 实用知识与技巧分享,涵盖基础、爬虫、数据分析等干货 本 Python 专栏聚焦实用知识,深入剖析基础语法、数据结构。分享爬虫、数据分析等热门领域实战技巧,辅以代码示例。无论新手入门还是进阶提升,都能在此收获满满干货,快速掌握 Python 编程精髓。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

tekin

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

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

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

打赏作者

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

抵扣说明:

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

余额充值