0

Can I make a similar code without f' and {} ? Python 3

hora = input() idx = hora.index(':') h = int(hora[:idx]) m = hora[idx+1:idx+3] if hora.endswith('AM'): if h < 10: hora = f'0{h}:{m}' else: hora = f'{h}:{m}' elif hora.endswith('PM'): hora = f'{h+12}:{m}' print(hora) This one converts 12 hr format to 24 hr format, deleting PM or AM and giving us a 24 hr format. But. Can I replicate this code with iteratives, slicings and index?

4th Jul 2020, 3:20 AM
Alaxos
Alaxos - avatar
2 Answers
+ 6
Hi there ZĂĄrate, f-strings are the most efficient and readable method of string formatting in python in the present world! - f-strings are introduced in python 3.6 and is best way for string formatting - These are some of the best articles on using f-strings: https://medium.com/swlh/string-formatting-in-python-6-things-to-know-about-f-strings-72fd38d96172 https://realpython.com/python-string-formatting/ - There are a few old methods too, concatenation is a (too much) beginner friendly method eg: hora = "0"+h+":"+m - You can use some other oldy methods too (not recommended): .format() it was the most widely used string formatting method just before f-strings were indroduced! eg: hora = "0{0}:{1}".format(h, m) I Would Recommend Learning and using f-strings because it's the most efficient and readable way to format strings in Python :)
4th Jul 2020, 3:59 AM
A C K
A C K - avatar
+ 8
You are actually already kind of using them. You find the index of the colon character iteratively, underneath. You assign the h and m variable by slicing the hora string using the index... Why would you want to complicate it? :)
4th Jul 2020, 3:58 AM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar