string库的使用!☃️

string库的使用

1.基本使用方法

1.1 字符串常量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import string

# 所有小写字母
print(string.ascii_lowercase)

# 所有大写字母
print(string.ascii_uppercase)

# 所有字母
print(string.ascii_letters)

# 所有数字
print(string.digits)

# 所有标点符号
print(string.punctuation)

# 所有可打印字符
print(string.printable)

# 所有空白字符
print(string.whitespace)

1.2 基本使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import string

# 检查字符串是否只包含字母
s = "HelloWorld"
print(all(c in string.ascii_letters for c in s)) # 输出 True

# 删除字符串中的标点符号
s = "Hello, World!"
print("".join(c for c in s if c not in string.punctuation)) # 输出 HelloWorld

# 格式化字符串
name = "Alice"
age = 30
formatted_string = string.Template('$name is $age years old.')
print(formatted_string.substitute(name=name, age=age)) # 输出 Alice is 30 years old.

# 使用模板字符串
from string import Template

name = "Alice"
age = 30
t = Template('$name is $age years old.')
print(t.substitute(name=name, age=age)) # 输出 Alice is 30 years old.

# 字符串模板替换
s = "$who likes $what"
d = {'who': 'Alice', 'what': 'Python'}
print(string.Template(s).safe_substitute(d)) # 输出 Alice likes Python

2.具体方法

2.1 join

join() 方法是 Python 中字符串对象的一个方法,用于将可迭代对象(如列表、元组等)中的元素连接成一个字符串。具体用法如下:

1
separator_string.join(iterable)

其中:

  • separator_string 是用于连接的字符串,它将插入到可迭代对象中的每个元素之间。
  • iterable 是一个可迭代的对象,包含需要连接的元素。

下面是一些示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 使用 join 方法将列表中的字符串连接成一个新的字符串
my_list = ["Hello", "World", "Python"]
result = " ".join(my_list)
print(result) # 输出 Hello World Python

# 使用 join 方法将元组中的字符串连接成一个新的字符串
my_tuple = ("apple", "banana", "cherry")
result = ", ".join(my_tuple)
print(result) # 输出 apple, banana, cherry

# 使用 join 方法将集合中的字符串连接成一个新的字符串
my_set = {"red", "green", "blue"}
result = "; ".join(my_set)
print(result) # 输出 green; blue; red

# 使用 join 方法将字典中的键连接成一个新的字符串
my_dict = {"name": "Alice", "age": 30}
result = ", ".join(my_dict)
print(result) # 输出 name, age

2.2 find

find() 方法是 Python 字符串对象的一个方法,用于在字符串中查找子字符串,并返回第一次出现的索引位置。如果子字符串不存在,则返回 -1。具体用法如下:

1
str.find(sub[, start[, end]])

其中:

  • str 是原始字符串。
  • sub 是要查找的子字符串。
  • start 是可选参数,指定查找的起始位置,默认为 0。
  • end 是可选参数,指定查找的结束位置,默认为字符串的长度。

下面是一个示例:

1
2
3
4
5
6
7
8
9
10
11
my_string = "hello world"

# 查找子字符串
print(my_string.find("world")) # 输出 6
print(my_string.find("python")) # 输出 -1,因为子字符串不存在

# 从指定位置开始查找
print(my_string.find("o", 5)) # 输出 7,从索引 5 开始查找子字符串 "o"

# 在指定范围内查找
print(my_string.find("l", 3, 6)) # 输出 3,在索引 3 到 6 的范围内查找子字符串 "l"

string库的使用!☃️
https://yangchuanzhi20.github.io/2024/02/13/算法/python/python库的使用/python中string库/
作者
白色很哇塞
发布于
2024年2月13日
许可协议