543

What is the easiest way in Python to replace a character in a string?

For example:

text = "abcdefg";
text[1] = "Z";
           ^
0

16 Answers 16

736

Don't modify strings.

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

>>> s = list("Hello zorld")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[6] = 'W'
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello World'

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.

10
  • 18
    Those looking for speed/efficiency, read this Apr 19, 2017 at 20:27
  • 33
    "Don't modify strings." why
    – hacksoi
    Oct 10, 2018 at 21:14
  • 8
    "Create->modify->serialize->assign->free" more efficent than s[6]='W'? Hmm... Why other languages allow it, in spite of that "lot" of reasons? Interesting how a strange design can be defended (for love I suppose). Why not suggest adding a function MID(strVar,index,newChar) to Python core that direct accesses the char memory position, instead of unnecesarily byte shuffling with the whole string?
    – oscar
    Nov 27, 2018 at 18:37
  • 3
    @hacksoi, @oscar, the reason is quite simple: no need to refcount when passing pointers around to implement copy-on-modify, or outright copy the whole string in case someone wants to modify that string - this leads to speed increase in generic use. There is no need for things like MID due to slices: s[:index] + c + s[index+1:]
    – MultiSkill
    Dec 4, 2018 at 8:19
  • 7
    The link in the answer is dead. Mar 2, 2021 at 9:44
306

Fastest method?

There are three ways. For the speed seekers I recommend 'Method 2'

Method 1

Given by this answer

text = 'abcdefg'
new = list(text)
new[6] = 'W'
''.join(new)

Which is pretty slow compared to 'Method 2'

timeit.timeit("text = 'abcdefg'; s = list(text); s[6] = 'W'; ''.join(s)", number=1000000)
1.0411581993103027

Method 2 (FAST METHOD)

Given by this answer

text = 'abcdefg'
text = text[:1] + 'Z' + text[2:]

Which is much faster:

timeit.timeit("text = 'abcdefg'; text = text[:1] + 'Z' + text[2:]", number=1000000)
0.34651994705200195

Method 3:

Byte array:

timeit.timeit("text = 'abcdefg'; s = bytearray(text); s[1] = 'Z'; str(s)", number=1000000)
1.0387420654296875
13
  • 3
    Would be interesting to see how it fares against the bytearray method too.
    – gaborous
    Mar 7, 2015 at 20:47
  • 3
    Good suggestion. The bytearray method is also slower: timeit.timeit("text = 'abcdefg'; s = bytearray(text); s[1] = 'Z'; str(s)", number=1000000) twice as slow as the fastest one. Mar 9, 2015 at 12:54
  • 4
    Appreciate the tests, which make me rethink how I should manipulate Python strings.
    – user2558887
    Feb 23, 2016 at 6:07
  • 2
    Nice. Please Edit the answer to include method 3 too (bytearray). Apr 19, 2017 at 20:25
  • 2
    It should be noted that most of the time here is spent in the conversions... (string -> byte array). If you have many edits to make to the string, then the byte array method will be faster. Oct 30, 2018 at 11:25
152
new = text[:1] + 'Z' + text[2:]
2
  • 3
    If you don't understand why this works, see the answer below
    – Ooker
    Aug 11, 2015 at 15:29
  • 2
    @Ooker Referring to the answer "below" is a dangerous thing on StackExchange ;) Sep 2, 2022 at 14:26
57

Python strings are immutable, you change them by making a copy.
The easiest way to do what you want is probably:

text = "Z" + text[1:]

The text[1:] returns the string in text from position 1 to the end, positions count from 0 so '1' is the second character.

edit: You can use the same string slicing technique for any part of the string

text = text[:1] + "Z" + text[2:]

Or if the letter only appears once you can use the search and replace technique suggested below

1
  • I ment the 2nd character, IE. the character at place number 1 (as apposed to the 1st character, number 0)
    – kostia
    Aug 4, 2009 at 15:56
14

Starting with python 2.6 and python 3 you can use bytearrays which are mutable (can be changed element-wise unlike strings):

s = "abcdefg"
b_s = bytearray(s)
b_s[1] = "Z"
s = str(b_s)
print s
aZcdefg

edit: Changed str to s

edit2: As Two-Bit Alchemist mentioned in the comments, this code does not work with unicode.

4
  • 2
    This answer is incorrect. For one thing, it should be bytearray(s), not bytearray(str). For another, this will produce: TypeError: string argument without an encoding. If you specify an encoding, then you get TypeError: an integer is required. That's with Python 3 or Python 2's unicode. If you do this in Python 2 (with a corrected second line), it won't work for non-ASCII characters because they may not be just one byte. Try it with s = 'Héllo' and you will get 'He\xa9llo'. Nov 20, 2015 at 21:58
  • I tried this again on Python 2.7.9. I could not regenerate the error you mention (TypeError: string argument without an encoding).
    – Mahmoud
    Nov 23, 2015 at 9:34
  • That error only applies if you are using unicode. Try s = u'abcdefg'. Nov 23, 2015 at 14:47
  • 7
    DO NOT DO THIS. This method ignores the entire concept of string encodings, which means it only happens to work on ASCII characters. In this day and age you cannot assume ASCII, even if you're an English speaker in an English speaking country. Python3's biggest backward incompatibility, and in my opinion most important, is fixing this whole byte = string false equivalency. Do not bring it back.
    – Adam
    Aug 25, 2018 at 5:12
11

Strings are immutable in Python, which means you cannot change the existing string. But if you want to change any character in it, you could create a new string out it as follows,

def replace(s, position, character):
    return s[:position] + character + s[position+1:]

replace('King', 1, 'o')
// result: Kong

Note: If you give the position value greater than the length of the string, it will append the character at the end.

replace('Dog', 10, 's')
// result: Dogs

9

Like other people have said, generally Python strings are supposed to be immutable.

However, if you are using CPython, the implementation at python.org, it is possible to use ctypes to modify the string structure in memory.

Here is an example where I use the technique to clear a string.

Mark data as sensitive in python

I mention this for the sake of completeness, and this should be your last resort as it is hackish.

3
  • 8
    Last resort? If you ever do this you are suddenly branded as evil! Dec 16, 2011 at 13:49
  • @ChrisMorgan if your string contain a password, clearing it with s='' is not enough because the password is still written somewhere in memory. Clearing it through ctypes is the only way.
    – Cabu
    Aug 5, 2016 at 13:49
  • 2
    @Cabu I would never under any circumstances accept code that did that. If your data is sensitive and you care about security like this, str is not the right type for you. Just don’t use it. Use something like bytearray instead. (Better still, wrap it in something that lets you treat it more or less as an opaque data so that you genuinely can’t retrieve a str from it, to protect you from accidents. There might be a library for that. No idea.) Aug 9, 2016 at 1:09
9

This code is not mine. I couldn't recall the site form where, I took it. Interestingly, you can use this to replace one character or more with one or more charectors. Though this reply is very late, novices like me (anytime) might find it useful.

Change Text function.

mytext = 'Hello Zorld'
# change all Z(s) to "W"
while "Z" in mytext:
      # replace "Z" to "W"
      mytext = mytext.replace('Z', 'W')
print(mytext)
7
  • 14
    This doesn't answer the question. It isn't what was desired at all. Dec 16, 2011 at 13:44
  • 5
    This code is bad if you want to replace only the first l. mytext = mytext.replace('l', 'W') -> HeWWo Zorld
    – Ooker
    Aug 11, 2015 at 15:33
  • If you are seeking to surgically replace only 1 character (which I am) this fits the bill perfectly. Thanks! Oct 20, 2015 at 2:18
  • 2
    @ProfVersaggi That is absolutely false. See Ooker's comment above. Nov 21, 2015 at 16:27
  • 6
    @Ooker If you want to replace only first character you can use mytext = mytext.replace('l', 'W',1). Link to doc
    – Alex
    Jan 30, 2017 at 21:07
6

I like f-strings:

text = f'{text[:1]}Z{text[2:]}'

In my machine this method is 10% faster than the "fast method" of using + to concatenate strings:

>>> timeit.timeit("text = 'abcdefg'; text = text[:1] + 'Z' + text[2:]", number=1000000)
1.1691178000000093
>>> timeit.timeit("text = 'abcdefg'; text = f'{text[:1]}Z{text[2:]}'", number =1000000)
0.9047831999999971
>>>
1
  • 2
    This is an interesting approach. Please consider formatting the inline code using markdown and posting details regarding your benchmarks and testing.
    – chb
    May 3, 2021 at 0:24
3

Actually, with strings, you can do something like this:

oldStr = 'Hello World!'    
newStr = ''

for i in oldStr:  
    if 'a' < i < 'z':    
        newStr += chr(ord(i)-32)     
    else:      
        newStr += i
print(newStr)

'HELLO WORLD!'

Basically, I'm "adding"+"strings" together into a new string :).

1
  • 5
    This is going to be very slow because every concatenation has to produce a new string object, since they are immutable, which is what this question is about. Nov 20, 2015 at 21:59
0

if your world is 100% ascii/utf-8(a lot of use cases fit in that box):

b = bytearray(s, 'utf-8')
# process - e.g., lowercasing: 
#    b[0] = b[i+1] - 32
s = str(b, 'utf-8')

python 3.7.3

0

I would like to add another way of changing a character in a string.

>>> text = '~~~~~~~~~~~'
>>> text = text[:1] + (text[1:].replace(text[0], '+', 1))
'~+~~~~~~~~~'

How faster it is when compared to turning the string into list and replacing the ith value then joining again?.

List approach

>>> timeit.timeit("text = '~~~~~~~~~~~'; s = list(text); s[1] = '+'; ''.join(s)", number=1000000)
0.8268570480013295

My solution

>>> timeit.timeit("text = '~~~~~~~~~~~'; text=text[:1] + (text[1:].replace(text[0], '+', 1))", number=1000000)
0.588400217000526
1
  • You're doing a combination of "Method 2" from another answer and joining it with the "replace" answer. Then you're comparing it against the .join method (which isn't performant). Overall, this doesn't seem to add anything from a performance or newness perspective over the other answers.
    – horta
    Jul 7, 2021 at 14:48
0

A solution combining find and replace methods in a single line if statement could be:

```python
my_var = "stackoverflaw"
my_new_var = my_var.replace('a', 'o', 1) if my_var.find('s') != -1 else my_var
print(f"my_var = {my_var}")           # my_var = stackoverflaw
print(f"my_new_var = {my_new_var}")   # my_new_var = stackoverflow
```
0

try this :

old_string = "mba"
string_list = list(old_string)
string_list[2] = "e"
//Replace 3rd element

new_string = "".join(string_list)

print(new_string)

0

To replace a character in a string

You can use either of the method:

Method 1

In general,

string = f'{string[:index]}{replacing_character}{string[index+1:]}'

Here

text = f'{text[:1]}Z{text[2:]}'

Method 2

In general,

string = string[:index] + replacing_character + string[index+1:]

Here,

text = text[:1] + 'Z' + text[2:]
0

If you're changing only one character, then the answer from Jochen Ritzel that uses string slicing is the fastest (and most readable imo). However, if you're going to change multiple characters in a string by position that way doesn't scale well. In that case, there's a builtin array module that could be useful to convert the string mutable object and change the required characters. Obviously converting to a list (as done in the accepted answer) also works but it's very slow.

import array
text = "HXlYo wZrWd"
ix = [1, 3, 7, 9]
vs = ['e', 'l', 'o', 'l']

ar = array.array('u', text)     # convert `text` string to array.array object
for i,v in zip(ix, vs):
    ar[i] = v                   # change characters by index
out = ar.tounicode()            # convert back to string
print(out)  # Hello world

Not the answer you're looking for? Browse other questions tagged or ask your own question.