Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

22.11.2022 22:51 https://moodle.boun.edu.tr/pluginfile.php/1143175/mod_resource/content/1/w06b-str-format.

py

# -*- coding: utf-8 -*-

"""w06b_str_format.ipynb

Automatically generated by Colaboratory.

Original file is located at

https://colab.research.google.com/drive/1LApjvTjpBxQ8tezlOfEJMkQmGW5TGoFI

"""

# string formatting

# <string>.format(<sth>)

# f-string... f'<sth>'

# .format

print(''.format())

print('hello'.format())

print('hello {}'.format('world'))

print('hello {} {}'.format('world','!'))

s1='hello'

s2='world'

print('{h} {w} {h} {h} {h} {w}'.format(h=s1,w=s2))

#% :d decimal, :b binary, :e scientific, %s string %f float

print('{:d}{{{}}}'.format(5,6))

print('{:b}'.format(5))

print('{:e}'.format(5))

print('{:e}'.format(0.92178631289))

print('{:s}'.format('I am string'))

print('{:f}'.format(5))

# format strings

print('|{:>12}|'.format('hello'))

print('|{:>12}|'.format('wwwwworld'))

print('|{:<12}|'.format('hello'))

print('|{:<12}|'.format('wwwwworld'))

print('|{:!<12}|'.format('hello'))
print('|{:!<12}|'.format('wwwwworld'))

# format decimal numbers

print('|{:0>5d}|'.format(5))

print('|{:0<5d}|'.format(5))

# format float numbers

print('|{:f}|'.format(5.2))

print('|{:.4f}|'.format(5.2))

print('|{:.4f}|'.format(5.28210982198))

print('|{:8.4f}|'.format(5.28210982198))

# f-string

print(f'something something')

a=3

b=4

# f'{<expressions>}'

print(f'a:{a}')

print(f'average of a and b: {(a+b)*0.5}')

name=['a','b','c','d']

print(f'{name[-2:]}')

# f-string cont'd

a=3.4

print(f'{a:.4f}')

print(f'|{a:x>10}|')

print(f'|{(a+b)**4:x>10.4f}|')

https://moodle.boun.edu.tr/pluginfile.php/1143175/mod_resource/content/1/w06b-str-format.py 1/2
22.11.2022 22:51 https://moodle.boun.edu.tr/pluginfile.php/1143175/mod_resource/content/1/w06b-str-format.py
## print all subsets question

ll = ['a','b','c','d']

for i in range(2**len(ll)):

bin_str='{:b}'.format(i) # some string, i need to put zeros to the left

bin_str = '0'*(len(ll)-len(bin_str))+bin_str

for j in range(len(bin_str)):

if bin_str[j]=='1':

print(ll[j],end='')

print()

## print all subsets question

ll = ['a','b','c','d']

for i in range(2**len(ll)):

bin_str='{:b}'.format(i) # some string, i need to put zeros to the left

bin_str = f'{bin_str:0>{len(ll)}}'

print(bin_str)

for j in range(len(bin_str)):

if bin_str[j]=='1':

print(ll[j],end='')

print()

https://moodle.boun.edu.tr/pluginfile.php/1143175/mod_resource/content/1/w06b-str-format.py 2/2

You might also like