Print formatted string with variables [duplicate] - string

Python : xx = "p" + "y" + str(3) => xx == "py3"
How can I get the same result using Racket?
(string-append "racket" (number->string 5) " ")
Is there another way in Racket, similar to the Python example above, to append a number to a string?

$ racket
Welcome to Racket v5.3.5.
-> (~a "abc" "def")
"abcdef"
-> (~a "abc" 'xyz 7 )
"abcxyz7"
->

Python automatically coerces the number to a string, while Racket will not do so. Neither Racket nor Python will coerce the number into a string. That is why you must use number->string explicitly in Racket, and str() in Python ("p" + str(3)). You may also find Racket's format function to behave similarly to some uses of Python's % operator:
# Python
"py %d %f" % (3, 2.2)
;; Racket
(format "rkt ~a ~a" 3 2.2)
But there is no Racket nor Python equivalent to "foo" + 3 that I know of.
[Answer edited per my mistake. I was confusing Python behavior with JavaScript, misled by OP]

Related

About operator "x" in Perl

I am confused by the following output of the code:
print "1234567890" x (10+9)/10;
The output is
1.23456789012346e+188.
I know the code should be this in order to get the intended result:
"1234567890" x ((10+9)/10)
But why does the former code generate a float number but not a string? Isn't the operator "x" a string operator in Perl?
Well, let's see what perl treats that expression as using the B::Deparse module:
$ perl -MO=Deparse,-p -e 'print "1234567890" x (10+9)/10;'
print((3993258840062839 * 2**573));
Obviously it's evaluating it as a number. Maybe because of the division? Let's try taking that out.
$ perl -MO=Deparse,-p -e 'print "1234567890" x (10+9);'
print('1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890');
which looks about right. So, basically, it's printing out that number because you're treating that really long string as a number thanks to the division.
Note that x and / have the same precedence, and are left associative, so that a x b / c is treated as (a x b) / c.
http://perldoc.perl.org/perlop.html#Operator-Precedence-and-Associativity
x and / have the same precedence. So
print "1234567890" x (10+9)/10;
is equivalent to
print( ("1234567890" x (10+9)) / 10 );
Note that x is not only a string repetion operator. It can generate lists: (1) x 3 is (1, 1, 1)
x is a string operator, but you are using / on the string it produces, which numifies "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678912345678901234567890123456789012345678901234567890" and divides it by 10.
It seems that 1234467890 is concat'd 19 times, then divided by 10 which creates a float.

Specify Python 3 to not meddle with new line?

I have the following code in Python 3:
st = "a" + '\r\n\r\n\r\n' + "b"
print( st )
The output is the following:
I do not want Python to add a 'CR' for me - I need to be in control. Is there anything I can do about it?
The built-in method repr() will return the string without the newline formatting.
https://docs.python.org/3/library/functions.html#repr
>>> st = "a" + '\r\n\r\n\r\n' + "b"
>>> print(repr(st))
'a\r\n\r\n\r\nb'
Alternatively, you can use a raw string like as demonstrated below.
https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
>>> print("a" + r'\r\n\r\n' + "b")
a\r\n\r\nb
Except the last one, all others are there just because you are telling python to write them (\r for LF and \n for CR). If you refer to the CR LF then you can use:
print(st,end="\n")

How to debug print a variable (name) and its value in Nim?

During quick and dirty debugging, I often use expressions like:
echo "variable1: ", variable1, " variable2: ", variable2
How can I leverage Nim's macro system to avoid repeating the variable name?
You can use a varargs macro that iterates over the arguments, and generates an AST which prints both the node's string literal as well as its value. Something like this:
import macros
macro debug*(n: varargs[typed]): untyped =
result = newNimNode(nnkStmtList, n)
for i in 0..n.len-1:
if n[i].kind == nnkStrLit:
# pure string literals are written directly
result.add(newCall("write", newIdentNode("stdout"), n[i]))
else:
# other expressions are written in <expression>: <value> syntax
result.add(newCall("write", newIdentNode("stdout"), toStrLit(n[i])))
result.add(newCall("write", newIdentNode("stdout"), newStrLitNode(": ")))
result.add(newCall("write", newIdentNode("stdout"), n[i]))
if i != n.len-1:
# separate by ", "
result.add(newCall("write", newIdentNode("stdout"), newStrLitNode(", ")))
else:
# add newline
result.add(newCall("writeLine", newIdentNode("stdout"), newStrLitNode("")))
Example usage:
let x = 2
let y = 3
debug("hello", x, y, x*y)
Output:
hello, x: 1, y: 2, x * y: 6

Better Print statement in Python using format strings?

print("=" * 100 + '\n' + "Can I be more elegant?" + '\n' + "=" * 100)
Is there a better elegant to print this?
Output
========================
Can I be more elegant?
========================
If you're using 3.6 or later, you can use the cool new f-strings.
print(f"{'='*100}\nCan I be more elegant?\n{'='*100}")
Prior to that, you can use format.
print("{0}\nCan I be more elegant?\n{0}".format('='*100))
Your first example was better. print("We have x = %i" %x) because you are working with a string object. It takes less memory than working with 2 string objects and an int.
Since you are asking with a python3 tag, here is a newer format for python string formatting using str.format
dic = { 'x': '1'}
print("We have x = {x}".format(**dic))
or you can do this positionally:
print("The sum of 1 + 2 is {0}".format(1+2))
This also works with 2.6 and 2.7.

`.split` method in clojure returns unexpected results

For part of a class project I need to read in a file representing a graph in Clojure. Here is a link to an example file. The file structure for all the files I could possibly read in are such
c Unknown number of lines
c That start with "c" and are just comments
c The rest of the lines are edges
e 2 1
e 3 1
e 4 1
e 4 2
e 4 3
e 5 1
e 5 2
The issue that I am having is trying to split a line based on spaces. In my REPL I have done
finalproject.core> (.split "e 1 2" " ")
#<String[] [Ljava.lang.String;#180f214>
Which, I am not sure what it means exactly.. I think it refers to a memory locations of a String[] I am not sure why it is displayed like that though. If the insert a # in front of the split string, which I think denotes it is a regular expression I receive an error
finalproject.core> (.split "e 1 2" #" ")
ClassCastException java.util.regex.Pattern cannot be cast to java.lang.String
Currently my entire implementation of this module is, which I am pretty sure will work if I could properly use the split function.
(defn lineToEdge [line]
(cond (.startsWith line "e")
(let [split-line (.split line " ")
first-str (split-line 1)
second-str (split-line 2)]
((read-string first-str) (read-string second-str)))))
(defn readGraphFile [filename, numnodes]
(use 'clojure.java.io)
(let [edge-list
(with-open [rdr (reader filename)]
(doseq [line (line-seq rdr)]
(lineToEdge line)))]
(reduce add-edge (empty-graph numnodes) edge-list)))
I have not had a chance to test readGraphFile in any way but when I try to use lineToEdge with some dummy input I receive the error
finalproject.core> (lineToEdge "e 1 2")
ClassCastException [Ljava.lang.String; cannot be cast to clojure.lang.IFn
Suggestions as to where I went wrong?
In the following, your return value is an Array of type String.
finalproject.core> (.split "e 1 2" " ")
#<String[] [Ljava.lang.String;#180f214>
To use it more conveniently in Clojure, you can put it into a vector:
user=> (vec (.split "e 1 2" " "))
["e" "1" "2"]
You can also use the built in clojure.string namespace:
user=> (require '[clojure.string :as string])
nil
user=> (string/split "e 1 2" #" ")
["e" "1" "2"]
The source of your stack trace is here:
(let [split-line (.split line " ")
first-str (split-line 1)
second-str (split-line 2)] ...)
This gets a String Array, via .split, then attempts to call it as if it were a function. Perhaps you meant to use get here to access an element of the List by index? (get split-line 1) will get the element from split-line at index 1, etc.
You'll see another problem here:
((read-string first-str) (read-string second-str))
If I am reading your code properly, this will end up calling a number as if it were a function, with another number as an argument. Perhaps you intend to return a pair of numbers?
[(read-string first-str) (read-string second-str)]

Resources