Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing one character in a string

Tags:

python

string

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

For example:

text = "abcdefg"; text[1] = "Z";            ^ 
like image 831
kostia Avatar asked Aug 04 '09 15:08

kostia


People also ask

How do you replace a character in a string with a string?

The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.

How do you replace a single character in a string in Python?

replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).


2 Answers

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 
like image 34
Mehdi Nellen Avatar answered Oct 14 '22 18:10

Mehdi Nellen


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.

like image 56
scvalex Avatar answered Oct 14 '22 19:10

scvalex