Python 中是否有与 Ruby 字符串插值等效的函数?[重复]

2025-01-03 08:40:00
admin
原创
115
摘要:问题描述:Ruby 示例:name = "Spongebob Squarepants" puts "Who lives in a Pineapple under the sea? #{name}." 成功的 Python 字符串连接对我来说似乎很冗长。解决方案 1:P...

问题描述:

Ruby 示例:

name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? 
#{name}."

成功的 Python 字符串连接对我来说似乎很冗长。


解决方案 1:

Python 3.6 将添加类似于 Ruby 字符串插值的文字字符串插值。从该版本的 Python(计划于 2016 年底发布)开始,您将能够在“f 字符串”中包含表达式,例如

name = "Spongebob Squarepants"
print(f"Who lives in a Pineapple under the sea? {name}.")

在 3.6 之前,最接近这个的是

name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? %(name)s." % locals())

%运算符可用于Python 中的字符串插值。第一个操作数是要插值的字符串,第二个操作数可以有不同的类型,包括“映射”,将字段名称映射到要插值的值。在这里,我使用局部变量字典locals()将字段名称name作为局部变量映射到其值。

使用最新 Python 版本的方法的相同代码.format()如下所示:

name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))

还有以下string.Template课程:

tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
print(tmpl.substitute(name="Spongebob Squarepants"))

解决方案 2:

从 Python 2.6.X 开始你可能需要使用:

"my {0} string: {1}".format("cool", "Hello there!")

解决方案 3:

我开发了interpy包,它可以在 Python 中实现字符串插值

只需通过 安装它pip install interpy。然后# coding: interpy在文件开头添加该行!

例子:

#!/usr/bin/env python
# coding: interpy

name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? 
#{name}."

解决方案 4:

Python 的字符串插值类似于 C 的 printf()

如果你尝试:

name = "SpongeBob Squarepants"
print "Who lives in a Pineapple under the sea? %s" % name

标签%s将被变量替换name。您应该查看打印函数标签:http ://docs.python.org/library/functions.html

解决方案 5:

根据 PEP 498 中的规定,字符串插值将包含在 Python 3.6 中。您将能够执行以下操作:

name = 'Spongebob Squarepants'
print(f'Who lives in a Pineapple under the sea? 
{name}')

请注意,我讨厌海绵宝宝,因此写这篇文章有点痛苦。:)

解决方案 6:

您还可以拥有

name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? 
{name}.".format(name=name)

http://docs.python.org/2/library/string.html#formatstrings

解决方案 7:

import inspect
def s(template, **kwargs):
    "Usage: s(string, **locals())"
    if not kwargs:
        frame = inspect.currentframe()
        try:
            kwargs = frame.f_back.f_locals
        finally:
            del frame
        if not kwargs:
            kwargs = globals()
    return template.format(**kwargs)

用法:

a = 123
s('{a}', locals()) # print '123'
s('{a}') # it is equal to the above statement: print '123'
s('{b}') # raise an KeyError: b variable not found

PS:性能可能是一个问题。这对本地脚本有用,但对生产日志没有用。

重复:

  • Python 字符串格式化:% 与 .format

  • 在 Python 中,将表达式嵌入字符串的等价内容是什么?(例如 Ruby 中的“#{expr}”)

  • Ruby 中与 Python 中的 s= "hello, %s. Where is %s?" % ("John","Mary") 等价的是什么

  • Python 中是否有与 Ruby 的字符串插值等效的函数?

解决方案 8:

Python 3.6 及更新版本使用 f 字符串进行文字字符串插值:

name='world'
print(f"Hello {name}!")

解决方案 9:

对于旧版 Python(在 2.4 上测试),上面的解决方案指明了方向。您可以这样做:

import string

def try_interp():
    d = 1
    f = 1.1
    s = "s"
    print string.Template("d: $d f: $f s: $s").substitute(**locals())

try_interp()

你会得到

d: 1 f: 1.1 s: s
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   3975  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   2742  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Freshdesk、ClickUp、nTask、Hubstaff、Plutio、Productive、Targa、Bonsai、Wrike。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在项目管理过程中面临着诸多痛点,如任务分配不...
项目管理系统   80  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Monday、TeamGantt、Filestage、Chanty、Visor、Smartsheet、Productive、Quire、Planview。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多项目经理和团队在管理复杂项目时,常...
开源项目管理工具   88  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Smartsheet、GanttPRO、Backlog、Visor、ResourceGuru、Productive、Xebrio、Hive、Quire。在当今快节奏的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在选择项目管理工具时常常面临困惑:...
项目管理系统   77  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用