Is there a Python equivalent to Ruby symbols?
No, python doesn't have a symbol type.
However string literals are interned by default and other strings can be interned using the intern
function. So using string literals as keys in dictionaries is not less performant than using symbols in ruby.
iterating over non-interpolated Array of symbols python equivalent
In python you do
for key in [metric_hash["passed_count"], metric_hash["blocked_count"], metric_hash["untested_count"], metric_hash["failed_count"]:
That means that key
takes values from a list [0, 0, 0, 0]
. Do you see why?
Is there a python equivalent to the ruby inspect method?
Use repr
. It returns a string containing a printable representation of an object. (similar to Object#inspect
in Ruby)
>>> repr([1,"string", ':symbol', ['l', 'i', 's', 't']])
"[1, 'string', ':symbol', ['l', 'i', 's', 't']]"
BTW, there's no symbol literal (:symbol
) or single character string literal (?x
) in Python; replaced them with string literals in the above example.
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"))
What is the difference between a Ruby Hash and a Python dictionary?
Both Ruby's Hash and Python's dictionary represent a Map Abstract Data Type (ADT)
.. an associative array, map, symbol table, or dictionary is an abstract data type composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection.
Furthermore, both Hash and dictionary are implemented as Hash Tables which require that keys are hashable and equatable. Generally speaking, insert and delete and fetch operations on a hash table are O(1) amortized or "fast, independent of hash/dict size".
[A hash table] is a data structure used to implement an associative array, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found.
(Map implementations that use Trees, as opposed to Hash Tables, are found in persisted and functional programming contexts.)
Of course, there are also differences between Ruby and Python design choices and the specific/default Map implementations provided:
- Default behavior on missing key lookup:
nil
inHash
, exception indict
1 - Insertion-ordering guarantees: guaranteed in
Hash
(since Ruby 2.0), no guarantee indict
(until Python 3.6)1 - Being able to specify a default value generator:
Hash
only1 - Ability to use core mutable types (eg. lists) as keys:
Hash
only2 - Syntax used for Hash/dict Literals, etc..
The []
syntax support is common insofar as both languages provide syntactic sugar for an overloaded index operator, but is implemented differently underneath and has different semantics in the case of missing keys.
1 Python offers defaultdict
and OrderedDict
implementations as well which have different behavior/functionality from the standard dict
. These implementation allow default value generators, missing-key handling, and additional ordering guarantees that are not found in the standard dict
type.
2 Certain core types in Python (eg. list
and dict
) explicitly reject being hashable and thus they cannot be used as keys in a dictionary that is based on hashing. This is not strictly a difference of dict
itself and one can still use mutable custom types as keys, although such is discouraged in most cases.
PHP equivalent to Ruby symbol
PHP has definable constants, but that's not really very useful in this context.
So no. Use strings as keys.
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.
What does Ruby have that Python doesn't, and vice versa?
You can have code in the class definition in both Ruby and Python. However, in Ruby you have a reference to the class (self). In Python you don't have a reference to the class, as the class isn't defined yet.
An example:
class Kaka
puts self
end
self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python.
Related Topics
Is Shared Readonly Data Copied to Different Processes for Multiprocessing
How to Make a Call to an Executable from Python Script
Conda Command Will Prompt Error: "Bad Interpreter: No Such File or Directory"
How to Create a Reference to a Variable in Python
Difference Between Variables Inside and Outside of _Init_()
Find the Max of Two or More Columns with Pandas
Difference Between Exit() and Sys.Exit() in Python
Concatenate Rows of Two Dataframes in Pandas
Keyboard Interrupts with Python's Multiprocessing Pool
Authenticate from Linux to Windows SQL Server with Pyodbc
How to Directly Send a Python Output to Clipboard
Python Requests. 403 Forbidden
How to "Test" Nonetype in Python
How to Remove Non-Ascii Characters But Leave Periods and Spaces