Python3.4-文本-替换字符串中的子串

本文演示了如何使用 Python 的 string 模块替换字符串中的子串,包括直接使用字典赋值和安全替换功能,以及利用 locals() 函数进行关键字参数替换。
"""
python版本: 3.4
替换字符串中的子串
"""
import string

info = """姓名: $name,
年龄: $age,
博客: $blog,
http://${weibo},
$$帅
"""
#string.Template(template)
info_template = string.Template(info)

#以字典的方式一一赋值
info_dic={'name':'毕小朋','age':30,'blog':'http://blog.csdn.net/wirelessqa','weibo':"www.weibo.com/wirelessqa"}

#substitute(mapping, **kwds)
print(info_template.substitute(info_dic))
"""
>>
姓名: 毕小朋,
年龄: 30,
博客: http://blog.csdn.net/wirelessqa,
http://www.weibo.com,
$帅
"""

#转成字典后再赋值
info_dic2=dict(name='毕小朋',age=30,blog='http://blog.csdn.net/wirelessqa',weibo='www.weibo.com/wirelessqa')

print(info_template.substitute(info_dic2))
"""
>>
姓名: 毕小朋,
年龄: 30,
博客: http://blog.csdn.net/wirelessqa,
http://www.weibo.com,
$帅
"""

#safe_substitute(mapping, **kwds)
#当我们少一个键(weibo被拿掉了哦)时,查看结果如何
test_safe_substitute=dict(name='毕小朋',age=30,blog='http://blog.csdn.net/wirelessqa')

try:
	print(info_template.substitute(test_safe_substitute))
except KeyError:
	print("error: 映射中没有weibo这个键")

"""
>>
error: 映射中没有weibo这个键
"""
#使用safe_substitute(mapping, **kwds)
print(info_template.safe_substitute(test_safe_substitute))
"""
>>
姓名: 毕小朋,
年龄: 30,
博客: http://blog.csdn.net/wirelessqa,
http://${weibo},
$帅
"""

#locals()提供了基于字典的访问局部变量的方式
info = string.Template('老毕是$shuai,芳龄$age')
shuai='帅哥'
age=18
print(info.substitute(locals())) #>>老毕是帅哥,芳龄18

#使用关键字作为参数替换
info = string.Template('老毕喜欢年龄$age的$who')
for i in range(18,39):
	print(info.substitute(age=i,who='美女'))

"""
>>
老毕喜欢年龄18的美女
老毕喜欢年龄19的美女
老毕喜欢年龄20的美女
老毕喜欢年龄21的美女
....
老毕喜欢年龄38的美女
"""

#同时使用关键字参数和字典
for age in range(18,39):
	print(info.substitute(locals(),who='美女'))
"""
>>
老毕喜欢年龄18的美女
老毕喜欢年龄19的美女
老毕喜欢年龄20的美女
老毕喜欢年龄21的美女
....
老毕喜欢年龄38的美女
"""

订阅

微信搜索“毕小烦”或者扫描下面的二维码,即可订阅我的文章。

image.png

如果文章对你有帮助,请随手点个赞吧!

(完)

### 3.1 使用 `in` 和 `not in` 操作符 Python 提供了非常直观的方式判断字符串是否包含特定子串,即使用 `in` 和 `not in` 操作符。例如: ```python string = "hello, python" substring = "python" if substring in string: print("子串存在") else: print("子串不存在") ``` 这种方式简洁且高效,底层实现依赖于字符串对象的 `__contains__` 方法[^2]。 ### 3.2 使用 `str.find()` 方法 `str.find()` 方法可以用来查找子串字符串中的位置。如果找到子串,返回其起始索引;否则返回 `-1`。因此可以通过是否等于 `-1` 来判断是否包含子串: ```python "hello, python".find("llo") != -1 # 返回 True "hello, python".find("lol") != -1 # 返回 False ``` 该方法适用于需要同时判断子串存在性并获取其位置的场景[^3]。 ### 3.3 使用 `str.index()` 方法 `str.index()` 方法与 `find()` 类似,但当子串不存在时会抛出 `ValueError` 异常,因此在使用时需要注意异常处理: ```python try: "hello, python".index("python") print("子串存在") except ValueError: print("子串不存在") ``` 该方法适用于确定子串存在时的定位需求。 ### 3.4 使用正则表达式 `re.search()` 如果需要更复杂的匹配逻辑,例如忽略大小写、匹配模式等,可以使用 `re.search()` 方法: ```python import re if re.search("Python", "hello, python", re.IGNORECASE): print("子串存在") else: print("子串不存在") ``` 正则表达式提供了强大的文本匹配能力,适用于复杂的子串判断场景。 ### 3.5 使用 `str.count()` 方法 通过判断子串字符串中出现的次数是否大于 0,也可以实现判断功能: ```python if "hello, python".count("py") > 0: print("子串存在") else: print("子串不存在") ``` 虽然可以实现判断功能,但效率不如 `in` 或 `find()`,仅在需要统计子串出现次数时推荐使用。 ### 3.6 使用 `__contains__` 方法 字符串对象的 `__contains__` 方法是 `in` 操作符的底层实现,也可以直接调用: ```python "hello, python".__contains__("py") # 返回 True ``` 不推荐直接调用魔法方法,建议使用更直观的 `in` 操作符。 ### 3.7 使用 `operator.contains()` 函数 Python 的 `operator` 模块提供了一个 `contains()` 函数,其实现与 `in` 操作符一致: ```python from operator import contains contains("hello, python", "py") # 返回 True ``` 该方法适用于函数式编程风格的场景。 --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

毕小烦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值