xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Python 字符串插值 All In One

Python 字符串插值 All In One

Python 字符串中使用变量的 5 种方式

#!/usr/bin/env python3
# coding=utf-8

__author__ = 'xgqfrms'
__editor__ = 'vscode'
__version__ = '1.0.1'
__copyright__ = """
  Copyright (c) 2012-2050, xgqfrms; mailto:xgqfrms@xgqfrms.xyz
"""

"""
  /**
   *
   * @author xgqfrms
   * @license MIT
   * @copyright xgqfrms
   * @created 2022-08-17
   *
   * @description
   * @augments
   * @example
   * @link
   *
  */
"""


# variable & case sensitive language

usename = 'xgqfrms'
UserName = 'xgqfrms'

# Python 字符串插值 ???
author = "xgqfrms"
title = "CTO"

# 字符串与变量拼接 ✅
print('👨🏻‍💻' + author + ' is ' + title + '🐍🇨🇳🌎')

  1. 字符串与变量拼接 ✅
author = "xgqfrms"
title = "CTO"

print('👨🏻‍💻' + author + ' is ' + title + '🐍🇨🇳🌎')
# 👨🏻‍💻 xgqfrms is CTO 🐍🇨🇳🌎

  1. % 格式 ✅
author = "xgqfrms"
title = "CTO"

print("👨🏻‍💻 %s is %s 🐍🇨🇳🌎" %(author, title))
# 👨🏻‍💻 xgqfrms is CTO 🐍🇨🇳🌎
  1. strings.format()
author = "xgqfrms"
title = "CTO"

print("👨🏻‍💻 {var1} is {var2} 🐍🇨🇳🌎".format(var1 = author, var2 = title))
# 👨🏻‍💻 xgqfrms is CTO 🐍🇨🇳🌎
# OR
print("👨🏻‍💻 {author} is {title} 🐍🇨🇳🌎".format(author = author, title = title))
# 👨🏻‍💻 xgqfrms is CTO 🐍🇨🇳🌎
  1. f"strings"

PEP 498

author = "xgqfrms"
title = "CTO"

print(f"👨🏻‍💻 {author} is {title} 🐍🇨🇳🌎")
# 👨🏻‍💻 xgqfrms is CTO 🐍🇨🇳🌎
  1. Template & template.substitute / 模板字符串
# import Template
from string import Template

author = "xgqfrms"
title = "CTO"

template = Template('👨🏻‍💻 $var1 is $var2 🐍🇨🇳🌎')

print(template)
# <string.Template object at 0x7ff169dc70d0>

print(template.substitute(var1 = author, var2 = title))
# 👨🏻‍💻 xgqfrms is CTO 🐍🇨🇳🌎

substitute === 代替/ 替换

# import Template
from string import Template

author = "xgqfrms"
title = "CTO"

template = Template('👨🏻‍💻 $author is $title 🐍🇨🇳🌎')

print(template)
# <string.Template object at 0x7ff169dc70d0>

print(template.substitute(author = author, title = title))
# 👨🏻‍💻 xgqfrms is CTO 🐍🇨🇳🌎

refs

How to use the variable in Python String All In One

如何在 Python 字符串中使用变量

https://www.cnblogs.com/xgqfrms/p/17450505.html

https://www.python.org/community/logos/

https://www.runoob.com/python3/python3-string.html

https://juejin.cn/post/7132797960919711752



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @   xgqfrms  阅读(116)  评论(4编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
历史上的今天:
2021-08-17 Apple Watch Series 6 开启自带 GPS All In One
2021-08-17 element-ui & async-validator bug All In One
2021-08-17 element-ui & multi tabs bug All In One
2020-08-17 LeetCode & linked list
2020-08-17 how to install GitLab on Raspberry Pi OS
2020-08-17 UML online tools
2020-08-17 React Hooks 内部实现原理
点击右上角即可分享
微信分享提示