0
点赞
收藏
分享

微信扫一扫

Python内置模块-String

Python内置模块-String

一、模块介绍

String模块是Python的内置模块,提供了各种操作字符串的工具和函数。

二、模块导入

import string

三、字符串常量

  • ascii_letters:所有小写和大写ASCII字母
  • ascii_lowercase:所有小写ASCII字母
  • ascii_uppercase:所有大写ASCII字母
  • digits:所有的十进制数字
  • hexdigits:所有的十六进制数字
  • octdigits:所有的八进制数字
  • printable:所有的可打印字符
  • punctuation:所有的标点字符
  • whitespace:所有的空白字符

常量使用

import string

print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print(string.digits)
print(string.hexdigits)
print(string.octdigits)
print(string.printable)
print(string.punctuation)
print(string.whitespace)

结果

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
01234567
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 	

!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
 	


四、函数

1.string.capwords()

作用   将输入字符串按照单词边界进行分割,并将每个单词的首字母转换为大写,其余字母转换为小写

语法

string.capwords(s, sep=None)

参数

  • s:要处理的字符串
  • sep:可用于指定单词之间的分隔符,默认情况下,capwords使用空格作为分隔符

示例

  • 基本使用
import string

# 基本使用,将每个单词的首字母大写
s = "hello world"
print(string.capwords(s))  # 输出: Hello World
  • 指定分隔符
import string

# 指定分隔符为逗号
s = "hello,world,this,is,a,test"
print(string.capwords(s, sep=','))  # 输出: Hello,World,This,Is,A,Test
  • 处理混合大小写的字符串
import string

# 处理混合大小写的字符串
s = "HELLO world, tHIS iS a TeST"
print(string.capwords(s))  # 输出: Hello World, This Is A Test

五、字符串模板

string.Template类提供了一个简单的方法来替换字符串中的特定标记,在使用格式化字符串时很有用。

from string import Template

# 创建一个模板
tmpl = Template("Hello, $name!$greeting")

# 使用字典进行替换
print(tmpl.substitute(name="张三", greeting="祝你今天愉快"))

# 使用关键字参数进行替换
print(tmpl.substitute(name="李四", greeting="你好吗?"))

结果

Hello, 张三!祝你今天愉快
Hello, 李四!你好吗?
举报

相关推荐

0 条评论