11. String Objects

11.1 Strings

  • Strings are first-class objects in Python 3.

  • Some useful string methods: upper(), swapcase(), format().

  • Strings can be enclosed using

    • '  '

    • "  "

    • '''   '''

  • Strings can be assigned as a variable, and format can be used on the variable as well.

    • s = 'Hello, World {}'

    • s.format(100).

11.2 More string methods

  • Case related: upper(), lower(), capitalize(), title(), swap(), casefold()

  • Strings are immutable, it can’t be changed. If you change the string using a method, it’s a different object.

  • Concatenate strings:

    1. s1 + s2.

    2. `s3 = ‘this string’ ‘ that string’

  • For details on string methods, see documentation

11.3 Format

  • Python has rich string-formatting capabilities.

  • format() method is used to format strings.

x = 42
print('the number is {}'.format(x))
  • Use formatting instructions are in the documentation

  • Examples:

    • {:,} formats a number with appropriate commas

    • {:.3f} fixes three decimal places

    • {:x} for hexadecimal

  • If Python > 3.6, you can use f-strings. All formatting methods work with f-strings as well.

11.4 Split and join

  • Strings can be split using the split() method:

s = 'This is a long string with a bunch of words in it.'
print(s.split())

Output:

['This', 'is', 'a', 'long', 'string', 'with', 'a', 'bunch', 'of', 'words', 'in', 'it.']
  • This can be joined using the join() method:

s = 'This is a long string with a bunch of words in it.'
l = s.split()
s2 = ' -- '.join(l)
print(s2)

Output:

This -- is -- a -- long -- string -- with -- a -- bunch -- of -- words -- in -- it.