DEV Community

Cover image for Python modify string

Posted on

Python modify string

In the Python programming language strings can be modified. In order to modify the original string you have method calls available.

Some functions are replace() and find(). But you can also use list() and *join() on strings. We'll show some examples below

substring and combined

You can get part of a string (a substring) or combine strings.

      >>> a = 'abcde'
      >>> b = 'fghij'
      >>> c = a[1:3] + b[2:5] + 'end'
      >>> c
      'Bchij end'


The replace function lets you replace the original string with a new string

      >>> a = 'aaabbbcccddd'
      >>> a.replace('aaa','xxx')

Combination find() and substring

Find a string inside a string

      >>> a = 'aaaxbbbcccxddd'
      >>> where = a.find('x')
      >>> where
      >>> a[:where] + 'ttttt' + a[where:]

The above three methods, although both modify the source string, in fact, they are not modified directly in the place, just create a new string object

Use the modified list

You may need to modify the long text and turn it into multiple strings (list).

      >>> a = 'aaaxbbbcccxddd'
      >>> b = list(a)
      >>> b
      [ 'A', 'a', 'a', 'x', 'b', 'b', 'b', 'c', 'c', 'c', 'x', 'd', ' d ',' d ']
      >>> b [2] = 'x'
      >>> b [7] = 'x'
      >>> b
      [ 'A', 'a', 'x', 'x', 'b', 'b', 'b', 'x', 'c', 'c', 'x', 'd', ' d ',' d ']
      >>> a = ''.join (b)
      >>> a

Top comments (0)