Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'in-place' string modifications in Python

Tags:

python

string

In Python, strings are immutable.

What is the standard idiom to walk through a string character-by-character and modify it?

The only methods I can think of are some genuinely stanky hacks related to joining against a result string.

--

In C:

for(int i = 0; i < strlen(s); i++) {    s[i] = F(s[i]); } 

This is super expressive and says exactly what I am doing. That is what I am looking for.

like image 465
Paul Nathan Avatar asked Aug 11 '10 23:08

Paul Nathan


People also ask

Can you modify a string in place in Python?

Strings in Python are immutable. Therefore, we cannot modify strings in place.

How do I modify string in Python?

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.


1 Answers

Don't use a string, use something mutable like bytearray:

#!/usr/bin/python  s = bytearray("my dog has fleas") for n in xrange(len(s)):     s[n] = chr(s[n]).upper() print s 

Results in:

MY DOG HAS FLEAS 

Edit:

Since this is a bytearray, you aren't (necessarily) working with characters. You're working with bytes. So this works too:

s = bytearray("\x81\x82\x83") for n in xrange(len(s)):     s[n] = s[n] + 1 print repr(s) 

gives:

bytearray(b'\x82\x83\x84') 

If you want to modify characters in a Unicode string, you'd maybe want to work with memoryview, though that doesn't support Unicode directly.

like image 183
bstpierre Avatar answered Sep 17 '22 13:09

bstpierre