Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a character from a certain index [duplicate]

How can I replace a character in a string from a certain index? For example, I want to get the middle character from a string, like abc, and if the character is not equal to the character the user specifies, then I want to replace it.

Something like this maybe?

middle = ? # (I don't know how to get the middle of a string)  if str[middle] != char:     str[middle].replace('') 
like image 600
Jordan Baron Avatar asked Jan 19 '17 22:01

Jordan Baron


People also ask

How do I replace a character at a particular index 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).

How do I remove a character from a specific index?

The most common approach to removing a character from a string at the specific index is using slicing. Here's a simple example that returns the new string with character at given index i removed from the string s .

How do I change the value of a specific index?

The first method is by using the substr() method. And in the second method, we will convert the string to an array and replace the character at the index. Both methods are described below: Using the substr() method: The substr() method is used to extract a sub-string from a given starting index to another index.


1 Answers

As strings are immutable in Python, just create a new string which includes the value at the desired index.

Assuming you have a string s, perhaps s = "mystring"

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:] 

You can find the middle by dividing your string length by 2 len(s)/2

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' 
like image 168
ti7 Avatar answered Sep 22 '22 18:09

ti7