Speed up development with full-stack environments for every branch.

Learn More

Strings in python

788 Runs 4748 Views 1407 Copies
Saved

Saved

sundip 66

sundip
published 4 years ago

import string 

###
# CONSTANTS
# http://docs.python.org/3/library/string.html#string-constants
###
print string.ascii_letters
print string.ascii_lowercase
print string.ascii_uppercase
print string.digits
print string.hexdigits
print string.octdigits
print string.punctuation
print string.printable
print string.whitespace



###
# STRING FORMATTING
# http://docs.python.org/3/library/string.html#string-formatting
###
# Accessing arguments by position:
print '{0}, {1}, {2}'.format('a', 'b', 'c')
print '{}, {}, {}'.format('a', 'b', 'c')  # 2.7+ only
print '{2}, {1}, {0}'.format('a', 'b', 'c')
print '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
print '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated


#
# Accessing arguments by name:
#
print 'Coordinates: {latitude}, {longitude}'.format(
  latitude='37.24N', longitude='-115.81W')


coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
'Coordinates: {latitude}, {longitude}'.format(**coord)
print coord


#
# Accessing arguments' attributes:
#
c = 3-5j
print ('The complex number {0} is formed from the real part {0.real} '
 'and the imaginary part {0.imag}.').format(c)

class Point(object):
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __str__(self):
        return 'Point({self.x}, {self.y})'.format(self=self)

str(Point(4, 2))


#
# Accessing arguments' items:
#
coord = (3, 5)
print 'X: {0[0]};  Y: {0[1]}'.format(coord)


#
# Replacing %s and %r:
#
print "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')


#
# Aligning the text and specifying a width:
#
print '{:<30}'.format('left aligned')
print '{:>30}'.format('right aligned')
print '{:^30}'.format('centered')
print '{:*^30}'.format('centered')  # use '*' as a fill char


#
# Replacing %+f, %-f, and % f and specifying a sign:
#
'{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
'{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
'{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'


#
# Replacing %x and %o and converting the value to different bases:
#
  # format also supports binary numbers
print "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)

  # with 0x, 0o, or 0b as prefix:
print "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)


#
# Using the comma as a thousands separator:
#
print '{:,}'.format(1234567890)


#
# Expressing a percentage
#
points = 19.5
total = 22
print 'Correct answers: {:.2%}'.format(points/total)


#
# Using type-specific formatting
#
import datetime
d = datetime.datetime(2010, 7, 4, 12, 15, 58)
'{:%Y-%m-%d %H:%M:%S}'.format(d)
print d


#
# Nesting arguments and more complex statements
#
for align, text in zip('<^>', ['left', 'center', 'right']):
    '{0:{fill}{align}16}'.format(text, fill=align, align=align)


octets = [192, 168, 0, 1]
result = '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
print result

print int(result, 16)

width = 5
for num in range(5,12):
    for base in 'dXob':
        print '{0:{width}{base}}'.format(num, base=base, width=width),
    print
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).