4

Python で、式が埋め込まれた文字列ブロックを作成したいと考えています。
Ruby では、コードは次のようになります。

def get_val
  100
end

def testcode
s=<<EOS

This is a sample string that references a variable whose value is: #{get_val}
Incrementing the value: #{get_val + 1}

EOS
  puts s
end

testcode
4

6 に答える 6

5

更新: Python 3.6 以降、リテラル文字列補間を有効にするフォーマット済み文字列リテラル (f-strings)があります。f"..{get_val()+1}..."


によって提供される単純な文字列フォーマット以上のものが必要な場合は、str.format()モジュールを使用して Python 式を挿入できます。%templet

from templet import stringfunction

def get_val():
    return 100

@stringfunction
def testcode(get_val):
    """
    This is a sample string
    that references a function whose value is: ${ get_val() }
    Incrementing the value: ${ get_val() + 1 }
    """

print(testcode(get_val))

出力

This is a sample string
that references a function whose value is: 100
Incrementing the value: 101

@stringfunction を使用した Python テンプレート

于 2012-03-18T23:39:13.620 に答える
4

format メソッドの使用:

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 2.7+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'

名前でフォーマット:

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
于 2012-03-18T23:03:43.463 に答える
2

C および Ruby プログラマーとして、私は古典printf的なアプローチが好きです。

>>> x = 3
>>> 'Sample: %d' % (x + 1)
'Sample: 4'

または複数の引数の場合:

>>> 'Object %(obj)s lives at 0x%(addr)08x' % dict(obj=repr(x), addr=id(x))
'Object 3 lives at 0x0122c788'

人々がこれで私を打ちのめそうとしていることを、私はすでに感じています。しかし、Ruby でも同じように機能するので、これは特に素晴らしいと思います。

于 2012-03-18T23:13:58.060 に答える
2

使用format方法:

>>> get_val = 999
>>> 'This is the string containing the value of get_val which is {get_val}'.format(**locals())
'This is the string containing the value of get_val which is 999'

**localsローカル変数の辞書をキーワード引数として渡します。 文字列内の は、変数の値を{get_val}出力する場所を示します。get_val他の書式設定オプションがあります。メソッドのドキュメントを参照してください。format

これにより、Ruby の場合とほとんど同じになります。#(Rubyでは中かっこの前に置く必要があるという唯一の違いがあります#{get_val})。

incremented を出力する必要がある場合get_val、次の方法以外に印刷する方法はありません。

>>> 'This is the string containing the value of get_val+1 which is {get_val_incremented}'.format(get_val_incremented = get_val + 1,**locals())
'This is the string containing the value of get_val+1 which is 1000'
于 2012-03-18T23:02:13.340 に答える
2

現代の Python の同等のプログラムは f-strings を使用します。(f-string 構文は比較的最近追加されたものです。)

def get_val():
    return 100

def testcode():
    s = f"""

This is a sample string that references a variable whose value is: {get_val()}
Incrementing the value: {get_val() + 1}

"""
    print(s)

testcode()
于 2018-06-05T03:22:08.453 に答える
1

Polyglot.orgは、PHP、Perl、Python、Rubyに関するこれらのような多くの質問に答えます。

于 2012-03-19T00:23:28.433 に答える