Showing posts with label fstrings. Show all posts
Showing posts with label fstrings. Show all posts

Jun 25, 2021

Python3 fstrings

vars = 'abc'

print(f 'Variable  is : {vars}')

This is much better than 'Variable is : {}'.format(vars)

May 19, 2020

Python 2 Vs 3


Python 2Python 3
input() may store as int, string
raw_input() stores str always
input() function was fixed in Python 3 so that it always stores the user inputs as str
print "Hi"
print("Hi")
print("Hi")
3/2 ==> floor(1.5) => 1 (defaults to floor), return int3/2 ==> 1.5
Strings default stores as AsciiStrings default stores as unicode

Unicode is a superset of ASCII and hence, can encode more characters including foreign ones.
sorted(employees.items(), key=lambda(x,y): y['age'])sorted(employees.items(), key=lambda x: x[1]['age'])
AsyncIO
Fstrings
It is recommended to use __future__ imports it if you are planning Python 3.x support for your code
xrange() - Lazy evaluationrange() - Lazy evaluation
except NameError, err:except NameError as err:
my_generator = (letter for letter in 'abcdefg')

next(my_generator)
my_generator.next()
my_generator = (letter for letter in 'abcdefg')

next(my_generator)
print 'Python', python_version()

i = 1
print 'before: i =', i
print 'comprehension: ', [i for i in range(5)]
print 'after: i =', i

Python 2.7.6
before: i = 1
comprehension: [0, 1, 2, 3, 4]
after: i = 4
Python 3.x for-loop variables don’t leak into the global namespace anymore!

print ('Python', python_version())
i = 1
print 'before: i =', i
print 'comprehension: ', [i for i in range(5)]
print 'after: i =', i

Python 3.4.1
before: i = 1
comprehension: [0, 1, 2, 3, 4]
after: i = 1
print range(3)
print type(range(3))

[0, 1, 2]
<type 'list'>
print range(3)
print type(range(3))
print(list(range(3)))

range(0, 3)
<class 'range'>
[0, 1, 2]
round(15.5) # 16.0
round(16.5) # 17.0
Bankers rounding
round(15.5) # 16
round(16.5) # 16

Nov 11, 2019

Python fstrings

elem = 10
elem_index = 5

def to_lowercase(st):
return st.lower()

#Formatted string literals (f-strings)
#The idea behind f-strings is to make string interpolation simpler.
#f-strings are expressions evaluated at runtime rather than constant values
print(f'Index of element {elem} is {elem_index}')

#call functions from f-strings
print(f'String to lowercase: {to_lowercase("TEST_STRING")}')
print(f'String to lowercase: {"TEST_STRING".lower()}')

#Format - used in previous versions of python
print('Index of element {} is {}'.format(elem, elem_index))
elapsed = 23.5678
print(f"{__file__} executed in {elapsed:0.2f} seconds.")


Output:
Index of element 10 is 5 String to lowercase: test_string String to lowercase: test_string Index of element 10 is 5
main.py executed in 23.57 seconds.