Determining if a filename is greater than X characters

Alex Martelli aleax at aleax.it
Mon Aug 4 03:01:47 EDT 2003


hokiegal99 wrote:

> One last question and then I'll leave you guys alone for awhile: How
> would I append a string to the end of each file that I've truncated? I'd
> like to put '.txt' on the end, but I don't understand how to go about
> it. When I tried this:
> 
>   old_fname = files
>   new_fname = old_fname.append('.txt')
> 
> .txt was added as a string to the files list. Researching a bit on
> Google told me that in Python strings are unchangeable. So, how would I
> go about changing a string?

You cannot change a given string-object, any more than you can change
a given number-object -- the object 23 will always have value 23 (never
22 nor 24 nor any other number), the object 'foo' will always have
value 'foo' (never 'bar' nor 'foobar' nor any other string).

However, you can re-bind a name to refer to a different object than
the one it previously referred to.  Thus, for example:

    x = 23
    x = x + 1

this has not changed the number 23, whose value IS still 23, but name 
x now refers to a different number, namely, the number 24.  Similarly:

    x = 'foo'
    x = x + '.txt'

this has not changed the string 'foo', whose value IS still 'foo', but name 
x now refers to a different string, namely, the string 'foo.txt'.

The unchangeability of strings doesn't inhibit string manipulation any
more than the unchangeability of numbers inhibits arithmetics.  Simply,
operations on strings build and return new strings, just like operations
on numbers build and return new numbers, and in either case you may, if
you wish, re-bind some pre-existing name to refer to the new objects.


Alex





More information about the Python-list mailing list