How do I put a variable’s value inside a string (interpolate it into the string)?
plot.savefig('hanning(%d).pdf' % num)
The %
operator, when following a string, allows you to insert values into that string via format codes (the %d
in this case). For more details, see the Python documentation:
printf
-style String Formatting
How to interpolate variables in strings in JavaScript, without concatenation?
You can take advantage of Template Literals and use this syntax:
`String text ${expression}`
Template literals are enclosed by the back-tick (` `) (grave accent) instead of double or single quotes.
This feature has been introduced in ES2015 (ES6).
Example
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.
How neat is that?
Bonus:
It also allows for multi-line strings in javascript without escaping, which is great for templates:
return `
<div class="${foo}">
...
</div>
`;
Browser support:
As this syntax is not supported by older browsers (mostly Internet Explorer), you may want to use Babel/Webpack to transpile your code into ES5 to ensure it will run everywhere.
Side note:
Starting from IE8+ you can use basic string formatting inside console.log
:
console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.
Using variables inside strings
In C# 6 you can use string interpolation:
string name = "John";
string result = $"Hello {name}";
The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.
Interpolate or use a variable inside a string in javascript
Combine the variable into the string properly:
text: 'o consumo aumentou em '+qtd3+' luvas = '+qtd4+' caixas.'
Putting a variable into a string (quote)
You should use a string formatter here, or concatenation. For concatenation you'll have to convert an int
to a string
. You can't concatenate ints and strings together.
This will raise the following error should you try:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Formatting:
quote = "You are %d years old" % age
quote = "You are {} years old".format(age)
Concatenation (one way)
quote = "You are " + str(age) + " years old"
Edit: As noted by J.F. Sebastian in the comment(s) we can also do the following
In Python 3.6:
f"You are {age} years old"
Earlier versions of Python:
"You are {age} years old".format(**vars())
R variable inside a string
variable2 <- paste0("I am argument:",variable1,"text continue")
How do I put variables inside javascript strings?
Note, from 2015 onwards, just use backticks for templating
https://stackoverflow.com/a/37245773/294884
let a = `hello ${name}` // NOTE!!!!!!!! ` not ' or "
Note that it is a backtick, not a quote.
If you want to have something similar, you could create a function:
function parse(str) {
var args = [].slice.call(arguments, 1),
i = 0;
return str.replace(/%s/g, () => args[i++]);
}
Usage:
s = parse('hello %s, how are you doing', my_name);
This is only a simple example and does not take into account different kinds of data types (like %i
, etc) or escaping of %s
. But I hope it gives you some idea. I'm pretty sure there are also libraries out there which provide a function like this.
Insert variable values in the middle of a string
You can use string.Format
:
string template = "Hi We have these flights for you: {0}. Which one do you want";
string data = "A, B, C, D";
string message = string.Format(template, data);
You should load template
from your resource file and data
is your runtime values.
Be careful if you're translating to multiple languages, though: in some cases, you'll need different tokens (the {0}
) in different languages.
Related Topics
Passing Command-Line Arguments in C#
How to Turn Off or Handle Camelcasing in JSON Response ASP.NET Core
Wpf Databinding to Interface and Not Actual Object - Casting Possible
C# Static Variables - Scope and Persistence
Best Method to Obfuscate or Secure .Net Assemblies
Save Settings in a .Net Winforms Application
Why Won't Control Update/Refresh Mid-Process
Convert Datetime for MySQL Using C#
How to Capture the Mouse Move Event
How to Compare Only Date Components from Datetime in Ef
How to Copy a File to Another Path
How to Fix the Memory Leak in Ie Webbrowser Control
Restore a Minimized Window of Another Application
Serialize Property, But Do Not Deserialize Property in JSON.Net