首页 > 编程知识 正文

Python字符串操作大全

时间:2024-04-27 11:09:11 阅读:335095 作者:DHXK

1. 概述

字符串是Python最重要的数据类型之一,也是使用最为广泛的数据类型之一。Python对字符串的的操作非常灵活,不管是从字符串的基本操作到字符串的高级操作,都可以通过Python内置的函数或第三方库轻松完成。本文将从多个方面介绍Python字符串操作,包括字符串的基本操作、字符串的格式化、字符串的正则表达式、字符串的加密解密等等,为读者提供Python字符串操作的全景式认识。

2. 字符串的基本操作

Python中的字符串是不可变的,这意味着我们不能在原字符串上进行修改,必须要通过新的字符串来完成修改。下面是一些字符串的基本操作:

字符串的连接

string1 = "hello"
string2 = "world"
string3 = string1 + " " + string2
print(string3) # 输出 hello world

字符串的截取

string = "hello world"
print(string[0:5]) # 输出 hello
print(string[6:]) # 输出 world

字符串的分割

string = "hello,world"
print(string.split(",")) # 输出 ['hello', 'world']

字符串的查找

string = "hello world"
print(string.find("world")) # 输出 6

3. 字符串的格式化

字符串的格式化是指将字符串中的某些位置通过特定的符号进行替换,以达到指定的格式。Python的字符串格式化使用的是%运算符,格式化字符串的占位符有%s,%d,%f,%c等等。

示例代码:

name = "Tom"
age = 20
money = 100.00
print("我的名字是%s,我的年龄是%d岁,我的财富是%.2f元。" % (name, age, money))

# 输出结果:
# 我的名字是Tom,我的年龄是20岁,我的财富是100.00元。

4. 字符串的正则表达式

正则表达式是用来匹配字符串中某些特定的模式的表达式。Python内置的re模块提供了完整的正则表达式功能,包括对字符串的查找、替换、分割、匹配等等操作。以下是一些正则表达式的使用案例:

匹配手机号码

import re

phone = "13913179888"
pattern = "^1[3-9]d{9}$"
result = re.match(pattern, phone)
if result:
    print("手机号码格式正确")
else:
    print("手机号码格式错误")

替换字符串中的空格

import re

string = "hello   world"
pattern = "s+"
result = re.sub(pattern, "-", string)
print(result) # 输出 hello-world

5. 字符串的加密解密

字符串的加密解密是指将明文字符串通过某些算法转化为密文,并且可以通过特定的方法将密文重新还原为明文。Python中有丰富的加密解密相关的第三方库,如hashlib、pycrypto等等,以下是一些常用的加密解密方法:

MD5加密

import hashlib

string = "hello world"
md5 = hashlib.md5()
md5.update(string.encode("utf-8"))
print(md5.hexdigest()) # 输出 5eb63bbbe01eeed093cb22bb8f5acdc3

AES加密

from Crypto.Cipher import AES
import base64

key = "0123456789abcdef" # 16位或24位或32位,但要求加密解密用的key必须相同
string = "hello world" # 加密内容必须为16的倍数

# 加密
aes = AES.new(key.encode("utf-8"), AES.MODE_ECB)
encrypt_bytes = aes.encrypt(string.encode("utf-8"))
encrypted_string = base64.b64encode(encrypt_bytes).decode("utf-8")
print(encrypted_string) # 输出 qae+36/4nuBX1+uu4gvDpA==

# 解密
aes = AES.new(key.encode("utf-8"), AES.MODE_ECB)
decrypt_bytes = aes.decrypt(base64.b64decode(encrypted_string.encode("utf-8")))
decrypted_string = decrypt_bytes.decode("utf-8").rstrip("")
print(decrypted_string) # 输出 hello world

6. 总结

本文对Python字符串的多个方面进行了介绍,包括字符串的基本操作、字符串的格式化、字符串的正则表达式、字符串的加密解密等等。Python字符串操作非常灵活,可以通过内置函数或第三方库来完成各种操作,在日常编程中应用广泛。掌握Python字符串操作,可以提升编程的效率和代码的质量。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。