Does Python do variable interpolation similar to string #{var} in Ruby?
Python 3.6+ does have variable interpolation - prepend an f
to your string:
f"foo is {bar}"
For versions of Python below this (Python 2 - 3.5) you can use str.format
to pass in variables:
# Rather than this:
print("foo is #{bar}")
# You would do this:
print("foo is {}".format(bar))
# Or this:
print("foo is {bar}".format(bar=bar))
# Or this:
print("foo is %s" % (bar, ))
# Or even this:
print("foo is %(bar)s" % {"bar": bar})
Is there a Python equivalent to Ruby's string interpolation?
Python 3.6 will add literal string interpolation similar to Ruby's string interpolation. Starting with that version of Python (which is scheduled to be released by the end of 2016), you will be able to include expressions in "f-strings", e.g.
name = "Spongebob Squarepants"
print(f"Who lives in a Pineapple under the sea? {name}.")
Prior to 3.6, the closest you can get to this is
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? %(name)s." % locals())
The %
operator can be used for string interpolation in Python. The first operand is the string to be interpolated, the second can have different types including a "mapping", mapping field names to the values to be interpolated. Here I used the dictionary of local variables locals()
to map the field name name
to its value as a local variable.
The same code using the .format()
method of recent Python versions would look like this:
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
There is also the string.Template
class:
tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
print(tmpl.substitute(name="Spongebob Squarepants"))
Python string interpolation implementation
Language Design Is Not Just Solving Puzzles: ;)
http://www.artima.com/forums/flat.jsp?forum=106&thread=147358
Edit: PEP-0498 solves this issue!
The Template
class from the string
module, also does what I need (but more similar to the string format
method), in the end it also has the readability I seek, it also has the recommended explicitness, it's in the Standard Library and it can also be easily customized and extended.
http://docs.python.org/2/library/string.html?highlight=template#string.Template
from string import Template
name = 'Renata'
place = 'hospital'
job = 'Dr.'
how = 'glad'
header = '\nTo Ms. {name}:'
letter = Template("""
Hello Ms. $name.
I'm glad to inform, you've been
accepted in our $place, and $job Red
will ${how}ly recieve you tomorrow morning.
""")
print header.format(**vars())
print letter.substitute(vars())
The funny thing is that now I'm getting more fond of using {}
instead of $
and I still like the string_interpolation
module I came up with, because it's less typing than either one in the long run. LOL!
Run the code here:
http://labs.codecademy.com/BE3n/3#:workspace
What is Ruby equivalent of Python's `s= hello, %s. Where is %s? % ( John , Mary )`
The easiest way is string interpolation. You can inject little pieces of Ruby code directly into your strings.
name1 = "John"
name2 = "Mary"
"hello, #{name1}. Where is #{name2}?"
You can also do format strings in Ruby.
"hello, %s. Where is %s?" % ["John", "Mary"]
Remember to use square brackets there. Ruby doesn't have tuples, just arrays, and those use square brackets.
Formatting multiple %s with a single variable
If you know for sure you're subbing %s
you can do it like this:
var = "house"
tup = (var,)
txt = "%s some %s words %s"
print txt % (tup * txt.count("%s"))
But a better solution is to use str.format()
which uses a different syntax, but lets you specify items by number, so you can reuse them:
var = "house"
txt = "{0} some {0} words {0}"
print txt.format(var)
In Ruby, can you perform string interpolation on data read from a file?
Instead of interpolating, you could use erb
. This blog gives simple example of ERB usage,
require 'erb'
name = "Rasmus"
template_string = "My name is <%= name %>"
template = ERB.new template_string
puts template.result # prints "My name is Rasmus"
Kernel#eval
could be used, too. But most of the time you want to use a simple template system like erb
.
How to build/concatenate strings in JavaScript?
With ES6, you can use
Template strings:
var username = 'craig';
console.log(`hello ${username}`);
ES5 and below:
use the
+
operatorvar username = 'craig';
var joined = 'hello ' + username;String's
concat(..)
var username = 'craig';
var joined = 'hello '.concat(username);
Alternatively, use Array methods:
join(..)
:var username = 'craig';
var joined = ['hello', username].join(' ');Or even fancier,
reduce(..)
combined with any of the above:var a = ['hello', 'world', 'and', 'the', 'milky', 'way'];
var b = a.reduce(function(pre, next) {
return pre + ' ' + next;
});
console.log(b); // hello world and the milky way
Related Topics
How to Open Process Again in Linux Terminal
To Read Line from File Without Getting "\N" Appended at the End
How to Upload File with Python Requests
Element-Wise Addition of 2 Lists
Error: Pandas Hashtable Keyerror
How Accurate Is Python's Time.Sleep()
Import Error: No Module Name Urllib2
How to Merge Multiple Dicts with Same Key or Different Key
Using Pip to Install Packages to Anaconda Environment
Remove Unwanted Parts from Strings in a Column
How to Install Python 3.6.5 on My Ubuntu 19.10 That Already Contains Python 3.7.5
Scheduling a Regular Event: Cron/Cron Alternatives (Including Celery)
Custom Sorting in Pandas Dataframe
Converting a Pandas Groupby Output from Series to Dataframe
Converting a String Representation of a List into an Actual List Object
How to Get List of Values from Dict
Why Do I Get "Typeerror: 'Str' Object Is Not Callable" with This Code