S1M0N_H
S1M0N_H

Reputation: 139

Python - use lists instead of strings?

From an S.O answer:

"Don't modify strings.

Work with them as lists; turn them into strings only when needed.

... code sample ...

Python strings are immutable (i.e. they can't be modified). There are a lot of reasons for this. Use lists until you have no choice, only then turn them into strings."

Is this considered best practice?

I find it a bit odd that Python has methods that return new modified strings (such as upper(), title(), replace() etc.) but doesn't have an insert method that returns a new string. Have I missed such a method?

Edit: I'm trying to rename files by inserting a character:

import os
for i in os.listdir('.'):
    i.insert(3, '_')

Which doesn't work due to immutability. Adding to the beginning of a string works fine though:

for i in os.listdir('.'):
    os.rename(i, 'some_random_string' + i)

Edit2: the solution:

>>> for i in os.listdir('.'):                                                │··
...  os.rename(i, i[:4] + '_' + i[4:])

Slicing certainly is nice and solves my problem, but is there a logical explanation why there is no insert() method that returns a new string?

Thanks for the help.

Upvotes: 0

Views: 234

Answers (3)

pyrrrat
pyrrrat

Reputation: 359

You can define a generic function that works on any sequence (strings, lists, tuples, etc.) using the slice syntax:

def insert(s, c, p):
    return s[:p] + c + s[p:]

insert('FILE1', '_', 4)
> 'FILE_1'

Upvotes: 0

Bryan Oakley
Bryan Oakley

Reputation: 386230

It's at least arguably a best practice if you are doing a very large number of modifications to a string. It is not a general purpose best practice. It's simply a useful technique for solving performance problems when doing heavy string manipulation.

My advice is, don't do it until performance becomes an issue.

Upvotes: 2

Max Shron
Max Shron

Reputation: 966

If you want to insert at a particular spot, you can use slices and +. For example:

a = "hello"
b = a[:2] + '_S1M0N_' + a[2:]

then b will be equal to he_S1M0N_llo.

Upvotes: 2

Related Questions