change specific indexes in string to same value python

  • Last Update :
  • Techknowledgy :

You can quickly (and obviously) replace a portion at a desired index by placing it between "slices" of the original.

s = s[: index] + newstring + s[index + 1: ]

If you're getting mystery inputs, you should take care to handle indices outside the expected range

def replacer(s, newstring, index, nofail = False):
   # raise an error
if index is outside of the string
if not nofail and index not in range(len(s)):
   raise ValueError("index outside given string")

#
if not erroring, but the index is still not in the correct range..
if index < 0: # add it to the beginning
return newstring + s
if index > len(s): # add it to the end
return s + newstring

# insert the new string between "slices" of the original
return s[: index] + newstring + s[index + 1: ]

This will work as

replacer("mystring", "12", 4)
'myst12ing'

You can't replace a letter in a string. Convert the string to a list, replace the letter, and convert it back to a string.

>>> s = list("Hello world") >>>
   s['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'] >>>
   s[int(len(s) / 2)] = '-' >>>
   s['H', 'e', 'l', 'l', 'o', '-', 'W', 'o', 'r', 'l', 'd'] >>>
   "".join(s)
'Hello-World'

You could for instance write a function:

def replace_str_index(text, index = 0, replacement = ''):
   return '%s%s%s' % (text[: index], replacement, text[index + 1: ])

And then for instance call it with:

new_string = replace_str_index(old_string, middle)

For instance:

replace_str_index('hello?bye', 5)
# Use slicing to extract those parts of the original string to be kept
s = s[: position] + replacement + s[position + length_of_replaced: ]

# Example: replace 'sat'
with 'slept'
text = "The cat sat on the mat"
text = text[: 8] + "slept" + text[11: ]

You can also Use below method if you have to replace string between specific index

def Replace_Substring_Between_Index(singleLine, stringToReplace = '', startPos = 0, endPos = 1):
   try:
   singleLine = singleLine[: startPos] + stringToReplace + singleLine[endPos: ]
except Exception as e:
   exception = "There is Exception at this step while calling replace_str_index method, Reason = " + str(e)
BuiltIn.log_to_console(exception)
return singleLine

Suggestion : 2

In the following example, we will take a string, and replace character at index=6 with e. To do this, we shall first convert the string to a list, then replace the item at given index with new character, and then join the list items to string.,In the following example, we will take a string, and replace character at index=6 with e.,In this tutorial of Python Examples, we learned how to replace a character at specific index in a string with a new character.,where character is the new character that has to be replaced with and position is the index at which we are replacing the character.

To replace a character with a given character at a specified index, you can use python string slicing as shown below:

string = string[: position] + character + string[position + 1: ]

Python Program

string = 'pythonhxamples'
position = 6
new_character = 'e'

string = string[: position] + new_character + string[position + 1: ]
print(string)

Output

pythonexamples

Suggestion : 3

August 4, 2021August 4, 2021

Simple example code replaces the character at a Specific Position. Where in the example we are taking a string, and replace the character at index=5 with X.

string = 'Python'
position = 5
new_character = 'X'

string = string[: position] + new_character + string[position + 1: ]
print(string)
2._
string = 'EyeHunte'
position = 7
new_character = 's'

temp = list(string)
temp[position] = new_character
string = "".join(temp)

print(string)

Replace multiple char using index positions in a string with the same character

string = 'Python'
list_of_indexes = [1, 3, 5]
new_character = 'Z'
res = ''

# Replace characters at index positions in list
for i in list_of_indexes:
   string = string[: i] + new_character + string[i + 1: ]

print(string)

Suggestion : 4

Last Updated : 22 Apr, 2020

The original string is: geeksforgeeks is best
The String after performing replace: ge * k * fo * ge * ks is best

Suggestion : 5

In the above example, we replaced the character at index position 3 in the string. For that, we sliced the string into three pieces i.e.,We can use the string slicing in python to replace the characters in a string by their index positions.,In this article, we will discuss how to replace a character in a string at a specific position. Then we will also see how to replace multiple characters in a string by index positions.,Then we joined the above slices, but instead of using the character at position 3, we used the replacement character ‘C’.

To replace a character at index position n in a string, split the string into three sections: characters before nth character, the nth character, and the characters after the nth characters. Then join back the sliced pieces to create a new string but use instead of using the nth character, use the replacement character. For example,

sample_str = "This is a sample string"

n = 3
replacement = 'C'

# Replace character at nth index position
sample_str = sample_str[0: n] + replacement + sample_str[n + 1: ]

print(sample_str)

Output:

ThiC is a sample string

To avoid this kind of error, we have created a function,

def replace_char_at_index(org_str, index, replacement):
   ''
' Replace character at index in string org_str with the
given replacement character.
''
'
new_str = org_str
if index < len(org_str):
   new_str = org_str[0: index] + replacement + org_str[index + 1: ]
return new_str

Let’s try to replace a character at index position, which is out of bounds,

sample_str = "This is a sample string"

# Replace character at 50 th index position
sample_str = replace_char_at_index(sample_str, 50, 'C')

print(sample_str)

We have few index positions in a list, and we want to replace all the characters at these index positions. To do that, we will iterate over all the index positions in the list. And for each index, replace the character at that index by slicing the string,

sample_str = "This is a sample string"

# Index positions
list_of_indexes = [1, 3, 5]

# Replace characters at index positions in list
for index in list_of_indexes:
   sample_str = replace_char_at_index(sample_str, index, 'C')

print(sample_str)

Suggestion : 6

October 19, 2021February 22, 2022

Let’s take a look at what that looks like:

# Replace an item at a particular index in a Python list
a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Mofidy first item
a_list[0] = 10
print(a_list)
# Returns: [10, 2, 3, 4, 5, 6, 7, 8, 9]

# Modify last item
a_list[-1] = 99
print(a_list)
# Returns: [10, 2, 3, 4, 5, 6, 7, 8, 99]

Let’s see what this looks like. In our list, the word apple is misspelled. We want to replace the misspelled version with the corrected version.

# Replace a particular item in a Python list
a_list = ['aple', 'orange', 'aple', 'banana', 'grape', 'aple']

for i in range(len(a_list)):
   if a_list[i] == 'aple':
   a_list[i] = 'apple'

print(a_list)

# Returns: ['apple', 'orange', 'apple', 'banana', 'grape', 'apple']

We’ll use the same example we used in the for loop, to help demonstrate how elegant a Python list comprehension can be:

# Replace a particular item in a Python list using a list comprehension
a_list = ['aple', 'orange', 'aple', 'banana', 'grape', 'aple']

a_list = ['apple'
   if item == 'aple'
   else item
   for item in a_list
]
print(a_list)

# Returns: ['apple', 'orange', 'apple', 'banana', 'grape', 'apple']

Let’s take a look at an example where we want to replace all known typos in a list with the word typo.

# Replace multiple items in a Python list with the same value
a_list = ['aple', 'ornge', 'aple', 'banana', 'grape', 'aple']
for i in range(len(a_list)):
   if a_list[i] in ['aple', 'ornge']:
   a_list[i] = 'typo'

print(a_list)
# Returns: ['typo', 'typo', 'typo', 'banana', 'grape', 'typo']

Instead of using a single if statement, we’ll nest in some elif statements that check for a value’s value before replacing.

# Replace multiple items in a Python list with the different values
a_list = ['aple', 'ornge', 'aple', 'banana', 'grape', 'aple']
for i in range(len(a_list)):
   if a_list[i] == 'aple':
   a_list[i] = 'apple'
elif a_list[i] == 'ornge':
   a_list[i] = 'orange'

print(a_list)
# Returns: ['apple', 'orange', 'apple', 'banana', 'grape', 'apple']