Better Print statement in Python using format strings? - python-3.x

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.

Related

Inserting values into strings in Python

I am trying to iterate over some integer values and insert them into an string which has to be in a weird format to work. The exact output (including the outer quotes) I need if the value was 64015 would be:
"param={\"zip\":\"64015\"}"
I have tried f string formatting but couldn't get it to work. It has problem with the backslashes and when I escaped them the output was not exactly like above string
Hopefully, I made myself clear enough.
You would have to escape the backslash and the double quotes seperately like this:
string = '"param={\\\"zip\\\":\\\"' + str(64015) + '\\\"}"'
The result of this is:
"param={\"zip\":\"64015\"}"
You can use alternate ways to delimit the outer string ('...', '''...''', """...""") or use str.format() or old style %-formatting syntax to get there (see f-style workaround at the end):
s = s = 'param={"zip":"' + str(64015) + '"}'
print(s)
s = '''param={"zip":"''' + str(64015) +'''"}'''
print(s)
s = """param={"zip":"64015"}""" # not suited for variable replacement
print(s)
s = 'param={{"zip":"{0}"}}'.format(64015)
print(s)
s = 'param={"zip":"%s"}' % 64015
print(s)
Output:
param={"zip":"64015"}
param={"zip":"64015"}
param={"zip":"64015"}
param={"zip":"64015"}
If you need any "\" in there simply drop a \\ in:
s = '"param={\\"zip\\":\\"' + str(64015) + '\\"}"'
print(s)
s = '''"param={\\"zip\\":\\"''' + str(64015) +'''\\"}"'''
print(s)
s = '"param={{\\"zip\\":\\"{0}\\"}}"'.format(64015)
print(s)
s = '"param={\\"zip\\":\\"%s\\"}"' % 64015
print(s)
Output:
"param={\"zip\":\"64015\"}"
"param={\"zip\":\"64015\"}"
"param={\"zip\":\"64015\"}"
"param={\"zip\":\"64015\"}"
The f-string workaround variant would look like so:
a = '\\"'
num = 64015
s = f'"param={{{a}zip{a}:{a}{num}{a}}}"'
and if printed also yields :
"param={\"zip\":\"64015\"}"
More on the topic can be found here: 'Custom string formatting' on python.org
I played around a bit with f-strings and .format() but ultimately got this to work:
foo = 90210
bar = '"param={\\"zip\\":\\"%s\\"}"' % (foo)
print(bar)
giving:
"param={\"zip\":\"90210\"}"
Hopefully someone can give you an f-string alternative. I kept running into unallowed "\" in my f-string attempts.
Is it only this?
a = "param={\"zip\":\"64015\"}"
b = a.split('=')
c = eval(b[1])
print(c)
print(c['zip'])
Result:
{'zip': '64015'}
64015
Please note that evaluating (eval()) strings from unknown source may
be dangerous! It may run the code that you are not expecting.

In Python 3.8 how to use a variable for print precision

I need to print a float with the precision I read from a file, e.g.,
float_var = 12.3456
precision_from_file = 2
print(f"float_var: {float_var:.2f}") ## Using precision_from_file instead of .2f
> output 12.35 , but the .2f came from precision_from_file
Any ideas will be much appreciated.
The answer can easily (embarrassing that I didn't think of it earlier) with f-strings by nesting the precision inside the {variable} curlies.
float_var = 12.3456
precision_from_file = 2
precision_str = '.' + str(precision_from_file) + 'f'
print(f"precision_str == {precision_str}")
print(f"float_var: {float_var:{precision_str}}")
Output:
> precision_str == .2f
> float_var: 12.35

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 do a backspace in python

I'm trying to figure out how to print a one line string while using a for loop. If there are other ways that you know of, I would appreciate the help. Thank you. Also, try edit off my code!
times = int(input("Enter a number: "))
print(times)
a = 0
for i in range(times+1):
print("*"*i)
a += i
print("Total stars: ")
print(a)
print("Equation: ")
for e in range(1,times+1):
print(e)
if e != times:
print("+")
else:
pass
Out:
Enter a number: 5
*
**
***
****
*****
Equation:
1
+
2
+
3
+
4
+
5
How do I make the equation in just one single line like this:
1+2+3+4+5
I don't think you can do a "backspace" after you've printed. At least erasing from the terminal isn't going to be done very easily. But you can build the string before you print it:
times = int(input("Enter a number: "))
print(times)
a = 0
for i in range(times+1):
print("*"*i)
a += i
print("Total stars: ")
print(a)
print("Equation: ")
equation_string = ""
for e in range(1,times+1):
equation_string += str(e)
if e != times:
equation_string += "+"
else:
pass
print(equation_string)
Basically, what happens is you store the temporary equation in equation_str so it's built like this:
1
1+
1+2
1+2+
...
And then you print equation_str once it's completely built. The output of the modified program is this
Enter a number: 5
5
*
**
***
****
*****
Total stars:
15
Equation:
1+2+3+4+5
Feel free to post a comment if anything is unclear.
Instead of your original for loop to print each number, try this:
output = '+'.join([str(i) for i in range(1, times + 1)])
print(output)
Explanation:
[str(i) for i in range(1, times + 1)] is a list comprehension that returns a list of all your numbers, converted to strings so that we can print them.
'+'.join(...) joins each element of your list, with a + in between each element.
Alternatively:
If you want a simple modification to your original code, you can simply suppress the newline from each print statement with the keyword paramater end, and set this to an empty string:
print(e, end='')
(Note that I am addressed the implied question, not the 'how do I do a backspace' question)
Too long for a comment, so I will post here.
The formatting options of python can come into good use, if you have a sequence you wish to format and print.
Consider the following...
>>> num = 5 # number of numbers to generate
>>> n = num-1 # one less used in generating format string
>>> times = [i for i in range(1,num+1)] # generate your numbers
>>> ("{}+"*n + "{}=").format(*times) # format your outputs
'1+2+3+4+5='
So although this doesn't answer your question, you can see that list comprehensions can be brought into play to generate your list of values, which can then be used in the format generation. The format string can also be produced with a l.c. but it gets pretty messy when you want to incorporate string elements like the + and = as shown in the above example.
I think you are looking for the end parameter for the print function - i.e. print(e, end='') which prints each value of e as it arrives followed by no space or newline.

Reversing a number using recursion

I was tasked with reversing an integer recursively. I have an idea of how to formulate my base case but I'm unsure of what to put outside of the if statement. The parts I was unsure about are commented with question marks. With the first part, I don't know what to put and with the second part I'm unsure about whether it is correct or not.Thank you for the help.
Note: I'd like to avoid using external functions such as imports and things like these if possible.
def reverseDisplay(number):
if number < 10:
return number
return # ??????????
def main():
number = int(input("Enter a number: "))
print(number,end="") #???????????
reverseDisplay(number)
main()
I'm not going to give you the answer, but I'll give some hints. It looks like you don't want to convert it to a string -- this makes it a more interesting problem, but will result in some funky behavior. For example, reverseDisplay(100) = 1.
However, if you don't yet have a good handle on recursion, I would strongly recommend that you convert the input to a string and try to recursively reverse that string. Once you understand how to do that, an arithmetic approach will be much more straightforward.
Your base case is solid. A digit reversed is that same digit.
def reverseDisplay(n):
if n < 10:
return n
last_digit = # ??? 12345 -> 4
other_digits = # ??? You'll use last_digit for this. 12345 -> 1234
return last_digit * 10 ** ??? + reverseDisplay(???)
# ** is the exponent operator. If the last digit is 5, this is going to be 500...
# how many zeroes do we want? why?
If you don't want to use any string operations whatsoever, you might have to write your own function for getting the number of digits in an integer. Why? Where will you use it?
Imagine that you have a string 12345.
reverseDisplay(12345) is really
5 + reverseDisplay(1234) ->
4 + reverseDisplay(123) ->
3 + reverseDisplay(12) ->
2 + reverseDisplay(1) ->
1
Honestly, it might be a terrible idea, but who knows may be it will help:
Convert it to string.
Reverse the string using the recursion. Basically take char from the back, append to the front.
Parse it again.
Not the best performing solution, but a solution...
Otherwise there is gotta be some formula. For instance here:
https://math.stackexchange.com/questions/323268/formula-to-reverse-digits
Suppose you have a list of digits, that you want to turn into an int:
[1,2,3,4] -> 1234
You do this by 1*10^3 + 2*10^2 + 3*10^1 + 4.*10^0. The powers of 10 are exactly reversed in the case that you want to reverse the number. This is done as follows:
def reverse(n):
if n<10:
return n
return (n%10)*10**(int(math.log(n,10))) + reverse(n//10)
That math.log stuff simply determines the number of digits in the number, and therefore the power of 10 that should be multiplied.
Output:
In [78]: reverse(1234)
Out[78]: 4321
In [79]: reverse(123)
Out[79]: 321
In [80]: reverse(12)
Out[80]: 21
In [81]: reverse(1)
Out[81]: 1
In [82]: reverse(0)
Out[82]: 0
Does exactly what #GregS suggested in his comment. Key to reverse is to extract the last digit using the modulos operator and convert each extracted digit to a string, then simply join them back into the reverse of the string:
def reverseDisplay(number):
if number < 10:
return str(number)
return str(number % 10) + reverseDisplay(number / 10)
def main():
print (reverseDisplay(int(input("Enter a number: "))))
main()
Alternative method without using recursion:
def reverseDisplay(number):
return str(number)[::-1]

Resources