当前分类:python>>正文

Python字符串替换函数的基本使用方法

来源:互联网   更新时间:2023年7月24日  

Python 笔记

一、replace()

string.replace(old, new[, count])
# 将字符串中的Alice替换为Bob
str1 = "Hello, Alice. How are you, Alice?"
new_str1 = str1.replace("Alice", "Bob")
print(new_str1)  # Hello, Bob. How are you, Bob?

# 只替换一次,将Alice替换为Bob
str2 = "Hello, Alice. How are you, Alice?"
new_str2 = str2.replace("Alice", "Bob", 1)
print(new_str2)  # Hello, Bob. How are you, Alice?

二、translate()

string.translate(table)
# 将字符串中的数字替换为@
str3 = "12345"
translation = str.maketrans("0123456789", "@@@@@@@@@@")
new_str3 = str3.translate(translation)
print(new_str3)  # @@@@@

# 将字符串中的元音字母替换为*
str4 = "Hello, world!"
translation = str.maketrans("aeiouAEIOU", "*")
new_str4 = str4.translate(translation)
print(new_str4)  # H*ll*, w*rld!

三、re.sub()

re.sub(pattern, repl, string, count=0)
import re

# 将字符串中的Alice替换为Bob
str1 = "Hello, Alice. How are you, Alice?"
new_str1 = re.sub("Alice", "Bob", str1)
print(new_str1)  # Hello, Bob. How are you, Bob?

# 只替换一次,将Alice替换为Bob
str2 = "Hello, Alice. How are you, Alice?"
new_str2 = re.sub("Alice", "Bob", str2, 1)
print(new_str2)  # Hello, Bob. How are you, Alice?

四、小结

本文固定链接:https://6yhj.com/leku-p-5026.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: 智能AI