Problem
You have a string which you might have read from an external file. The string contains a significant amount of characters that you would like to automatically replace.
Possible Solutions
Replacing a single character with another
# define your string
str1 = 'This string contains lots of semi colons ;;;;'
# rep
print(str1.replace(';', ':'))
Here’s the output:
This string contains lots of semi colons ::::
Switch character in string in list
In this example we’ll replace all occurrences of multiple characters from a predefined list by a single character.
#replace multiple characters in list
str2 = 'This string contains lots of special characters ;;;;:::::&&&&&&$$$$'
rep_lst = [';', ':', '&', '$']
for i in rep_lst:
if i in str2:
str2 = str2.replace(i, ',')
print(str2)
Here’s the result:
This string contains lots of special characters ,,,,,,,,,,,,,,,,,,,
Replace the first character in a string
In this example, we’ll go ahead and flip the first character in the string. We can use the count parameter of the string replace() method to ensure that we’ll replace only the first occurrence of that char.
Here’s a very simple example:
# replace first string
str1 = 'This string contains lots of semi colons ;;;;'
print(str1.replace('T', 't', 1))
Here’s the result:
'this string contains lots of semi colons ;;;;'
Note that we are able to use the Python code provided in the next section to replace specific positions in the string. For the first character we’ll use the 0 position, and for the last, the -1 position.
Replace character at string in a specific position
In this example, we’ll switch the last character.
str1 = 'This string contains lots of semi colons ;;;;'
pos = -1
char = ':'
# convert the string to a list
str_lst = list (str1)
#assign the replacing character
str_lst[pos] = char
# convert list back to string
str1 = ''.join(str_lst)
print(str1)
Here’s our result:
This string contains lots of semi colons ;;;: