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 @ 2022-08-17 18:23  xgqfrms  阅读(107)  评论(4编辑  收藏  举报