可変補間

Dec 25 2022
変数補間は、時間の経過とともに変化する可能性のある値を含む動的文字列を作成するためにプログラミングで使用される一般的な手法です。これには、プレースホルダーを含む文字列を評価し、プレースホルダーを対応する値に置き換えることが含まれます。
UnsplashのRichard Horvathによる写真

変数補間は、時間の経過とともに変化する可能性のある値を含む動的文字列を作成するためにプログラミングで使用される一般的な手法です。これには、プレースホルダーを含む文字列を評価し、プレースホルダーを対応する値に置き換えることが含まれます。通常、プレースホルダーはシンボルまたはキーワードで表され、値は通常、コードで以前に定義された変数または式です。

formatPython では、次のメソッドを使用して変数補間を実現できます。

name = "John"
age = 30
# Interpolate the variables into the string using the format method
output_string = "Hello, my name is {name} and I am {age} years old.".format(name=name, age=age)
# The output string will be "Hello, my name is John and I am 30 years old."

let name = "John";
let age = 30;
// Interpolate the variables into the string using template literals
let outputString = `Hello, my name is ${name} and I am ${age} years old.`;
// The output string will be "Hello, my name is John and I am 30 years old."

変数補間は、さまざまなプログラミング言語で動的文字列を作成するための便利なツールです。動的 HTML やその他の種類のドキュメントを生成するためのテンプレートでよく使用されます。

いくつかの高度なヒント

パイソン:

  • f-strings を使用して、変数を直接文字列に補間します。
  • name = "John"
    age = 30
    message = f"Hello, my name is {name} and I am {age} years old."
    print(message)  # Output: "Hello, my name is John and I am 30 years old."
    

    name = "John"
    age = 30
    message = "Hello, my name is %s and I am %d years old." % (name, age)
    print(message)  # Output: "Hello, my name is John and I am 30 years old."
    

  • テンプレート リテラルを使用して、変数を文字列に直接補間します。
  • const name ="John";
    const age = 30;
    const message = `Hello, my name is ${name} and I am ${age} years old.`;
    console.log(message);  // Output: "Hello, my name is John and I am 30 years old."