Python实现文本添加超链接:变量替换失效问题求助
解决Python中超链接变量替换问题
你之前的问题在于直接把变量名new_test写进字符串里,Python会把它当作普通文本而非变量值来处理。下面给你几种简单可行的解决方法:
方法一:使用f-string(推荐,Python 3.6及以上版本支持)
这是最简洁直观的写法,在字符串前加f,然后用{}包裹变量即可:new_test='www.youtube.com/' hyperlink_format= f'<a href={new_test}>text of the link</a>' print(hyperlink_format)执行后就能得到你想要的结果:
<a href=www.youtube.com/>text of the link</a>方法二:正确使用str.format()
你之前的format写法参数有误,其实只需要一个参数就能搞定,调整字符串的占位符即可:new_test='www.youtube.com/' hyperlink_format= '<a href={}>text of the link</a>'.format(new_test) print(hyperlink_format)这里的
{}对应format方法里传入的new_test变量,完全满足你的需求。方法三:字符串拼接
直接把字符串片段和变量拼接起来,虽然不够优雅,但也能实现效果:new_test='www.youtube.com/' hyperlink_format= '<a href=' + new_test + '>text of the link</a>' print(hyperlink_format)
内容的提问来源于stack exchange,提问作者Phoenix
相关产品推荐
相关产品推荐

