欢迎访问宙启技术站
智能推送

Python中的String函数一览-包括字符串格式化、字符串拆分、字符串加密等常用操作

发布时间:2023-07-17 09:01:52

Python中的String函数涵盖了许多常用操作,包括字符串格式化、字符串拆分、字符串加密等。下面我们将对这些常用操作进行一一介绍。

1. 字符串格式化

字符串格式化是指通过将变量的值插入到字符串中指定的位置或占位符中来构建新的字符串。Python中的字符串格式化可以通过多种方式实现,其中比较常用的是使用百分号(%)和format()函数。

a) 使用百分号(%)进行格式化

示例代码:

name = 'John'
age = 25
print('My name is %s and I am %d years old.' % (name, age))

运行结果:

My name is John and I am 25 years old.

百分号后的字符指定了变量的类型,其中%s表示字符串,%d表示整数。

b) 使用format()函数进行格式化

示例代码:

name = 'John'
age = 25
print('My name is {} and I am {} years old.'.format(name, age))

运行结果:

My name is John and I am 25 years old.

大括号中的数字指定了变量在format()函数中的索引位置,从0开始计数。当大括号中不指定数字时,默认为按照顺序替换。

2. 字符串拆分

字符串拆分是指将一个字符串按照指定的分隔符进行拆分成多个子串。Python中提供了split()函数用于实现字符串拆分。

示例代码:

sentence = 'I love Python programming'
words = sentence.split(' ')
print(words)

运行结果:

['I', 'love', 'Python', 'programming']

split()函数的参数是分隔符,可以是空格、逗号等。

3. 字符串加密

字符串加密是指将明文字符串转换为一串看似随机的字符序列,用于保护信息的安全性。Python中常用的字符串加密方法有base64和hashlib。

a) base64加密

示例代码:

import base64

string = 'Hello World'
encoded_string = base64.b64encode(string.encode('utf-8'))
print(encoded_string.decode('utf-8'))

运行结果:

SGVsbG8gV29ybGQ=

b64encode()函数将明文字符串转换为base64编码的字符串,b64decode()函数用于解码。

b) hashlib加密

示例代码:

import hashlib

string = 'Hello World'
hashed_string = hashlib.sha256(string.encode('utf-8')).hexdigest()
print(hashed_string)

运行结果:

2ef7bde608ce5404e97d5f042f95f89f1c232871d2eafe76f3f244f46727b2db

sha256()函数将明文字符串进行SHA-256加密,hexdigest()函数将结果转换为十六进制表示。

以上是Python中常用的字符串函数,涵盖了字符串格式化、字符串拆分和字符串加密等常见操作。掌握这些函数,可以更加方便地操作和处理字符串数据。