Why one formatted String literals is able to print without print() but the other not?
>> price = 11.23
>> f"Price in Euro: {price}"
>> for article in ["bread", "butter", "tea"]:
print(f"{article:>10}:")
Interactive sessions print the result of the last top-level statement. A format string is an expression and thus has a result, but a for loop is not and produces no result to display.
>>> 3 # expression
3
>>> a = 3
>>> a # expresion
3
>>> a + 4 # expression
7
>>> if a:
... 9
>>> f"{a}" # expression
3
It's pretty unclear what you want to do with your code, but this should work
for article in ['bread', 'butter']:
print(f"{article}")
Can you please properly format your code and edit your question?
Related
I had the following print statement in my python2 program (after '-' sign) and replaced it with some more elaborate python3 code (after '+' sign). Is there a better i.e. more elegant way to do this?
- print("%(txn_processed)8d %(txn_skip)5d %(txn_ctr)5d")%accounts[account]
+ acc_ctrs = accounts[account]
+ processed = accounts[account]['txn_processed']
+ skipped = accounts[account]['txn_skip']
+ ctr = accounts[account]['txn_ctr']
+ print('%8d %5d %5d'%(processed, skipped, ctr))
The dictionary accounts has one entry per account with 3 counters in a sub dictionary. So I process the accounts in a for account in accounts: loop and separate the 3 counters into processed, skipped and sum. This is what the output looks like (specifically the last 2 lines):
Output to ofx (GnuCash version)
TRANSACTIONS: 248
IN: 2018-008-transactions-30-12-to-26-09.csv
OUT: 2018-008-transactions-30-12-to-26-09.ofx
accountnumber processed skip sum
NL89RABO0000000000 231 0 231
NL71RABO1111111111 1 16 17
My knowledge of python3 is limited. Hope you guys can help me out.
P.S. the python2 line returned an error message about NoneType and Dict.
Kind regards, Guus.
print is a function in python 3, but you have confusing parentheses:
Python 2 interpretation is as follows:
print ("%(txn_processed)8d %(txn_skip)5d %(txn_ctr)5d") % accounts[account]
# ^----------------------- argument to print ---------------------------------------^
In fact, these parens around a string were entirely unnecessary in python 2.
Python 3 interpretation is to treat parentheses as arguments, as any regular function/method:
print ("%(txn_processed)8d %(txn_skip)5d %(txn_ctr)5d") % accounts[account]
# ^------------- argument to print --------------^
And print returns None, and you are trying to call __rem__ on it. That's why you have an error.
All you need to do to fix it for Python 3 is to wrap everything in parentheses instead of just the string you'll be formatting:
print("%(txn_processed)8d %(txn_skip)5d %(txn_ctr)5d" % accounts[account])
# ^------------- argument to print ---------------------------------^
acc_ctrs = accounts[account]
print('%8d %5d %5d'%(
acc_ctrs['txn_processed'],
acc_ctrs['txn_skipped'],
acc_ctrs['txn_ctr']
))
To print dict in elegant way, use this:
import pprint
pprint.pprint(dict)
You'll get the output in readable way.
This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 3 years ago.
I'm new to python automation and wrote a script to get some port handles from Ixia and store into a list. I;m trynig to sort that port-handle where I see a problem.
I tried using the sort method but doesn;t work
>>> a
['1/1/11', '1/1/6']
>>> a.sort()
>>> a
['1/1/11', '1/1/6']
>>> d = a.sort()
>>> print(d)
None
>>>
Am i missing anything here .. kindly clarify
I want the output in the following format
1/1/6 1/1/11
Explanation
You are trying to sort a list of strings. Strings are naturally sorted in lexicographical_order, i.e. "10" < "11" < "2" < "5" < ..., so Python executes correctly what you want it to do. This being said, you need to transform your data into something that will be sorted as you want.
Solution
>>> a = ['1/1/11', '1/1/6']
>>> a
['1/1/11', '1/1/6']
>>> def to_tuple(string_representation):
... return tuple(int(i) for i in string_representation.split('/'))
...
>>> b = [to_tuple(element) for element in a]
>>> b.sort()
>>> b
[(1, 1, 6), (1, 1, 11)]
>>> a.sort(key=to_tuple)
>>> a
['1/1/6', '1/1/11']
Here we use the fact that tuple is sorted by default exactly how we want it to be sorted in your case (actually, it is also a lexicographical order, but now 11 is one element of a sequence and not two).
List b contains a transformed list, where each element is a tuple. And now sort will work as you want.
The second option, will be using a custom key operator. It is a function that returns a key to compare different elements of your list. In this case, key will be a corresponding tuple of integers and will be compared as you want.
Note 1
The second approach (with the key operator) will create an additional overhead during sorting as it will be called O(NlogN) times.
Note 2
You also tried using the result of sort function as a value, but it changes the given list in-place. If you want a sorted copy of your list, use sorted.
I am relatively new to python and I have to create a program that prints the middle character of a user-inputted string. Here is what I have:
#accept string from user then print middle character
x = input("Enter a string: ")
print(x[len(x)/2-1])
However I keep getting this error when I try to run the program:
"TypeError: string indices must be integers".
Im not sure how to fix this or how to get this program to work. Please help!
From your error I infer that you are using python 3.
In python 3 division between two integers returns a float:
>>> 3/2
1.5
>>> 4/2
2.0
But a indeces must be integers, so you get the error. To force an integer division you must use the // operator:
>>> 3//2
1
>>> 4//2
2
Alternatively you can use math.ceil or math.floor if you want more control on the rounding of the floats.
This is a way:
x = raw_input("Enter a string: " )
print (x[:len(x)//2])
I use Python3 and write result into a file like this:
with open(output,'w') as f:
f.write('Line count of the log files is: ' + str(line_count) + '. \n')
f.write() automatically returns # of characters written, is there a way to do not output it? I ask this because I do not want it output.
Thanks.
This is not unique to file.write(). The interactive interpreter prints the result of any evaluated expression that does not result in None.
>>> for i in range(3):
... i # expression evaluates to the value of i
...
0
1
2
>>>
Two things to note. First, these won't be displayed when you are not using the interactive interpreter, so it's safe to ignore.
Second, you can make the display go away by assigning the result. That turns the expression into a statement.
>>> for i in range(3):
... _ = i # underscore is a nice meaningless variable name
...
>>>
On websites like hackerrank, which I have just recently been introduced to, there are some problems where the input is:
1 5 9
And they want these to be different variables.
Is there a way to read this input with
input()
But then make the three parts of the input different variables?
I have tried:
list_input = input().split(' ')
But this only creates a list of strings.
Is there a better way to create different variables from only one line of input?
Thanks
One way you can do this:
>>> variables = input ("Enter an input separated by space: ")
Enter an input separated by space: 1 5 9
>>> variables
'1 5 9'
>>>
>>> variables = variables.split (' ')
>>> variables
['1', '5', '9']
>>> variables [1]
'5'
>>>
>>> for var in variables:
print (var)
1
5
9
>>>