Python замена элемента в строке по индексу

Python: Replace character in string by index position

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.

Table of Contents

Use Python string slicing to replace nth character in a string

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)

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.

Frequently Asked:

  1. Characters from index position 0 to 2.
  2. Character at index position 3
  3. Characters from index position 3 till the end of string.

Then we joined the above slices, but instead of using the character at position 3, we used the replacement character ‘C’.

Читайте также:  Javascript jquery div text

Python function to replace a character in a string by index position

The slicing approach is good to replace the nth character in a string. But what if somebody tries to replace a character at an index that doesn’t exist? That means if the given index position for replacement is greater than the number of characters in a string, then it can give unexpected results. Therefore we should always check if the given nth position is in the range or not.

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

Now let’s use this function to replace nth character in a string,

sample_str = "This is a sample string" # Replace character at 3rd index position sample_str = replace_char_at_index(sample_str, 3, 'C') print(sample_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 50th index position sample_str = replace_char_at_index(sample_str, 50, 'C') print(sample_str)

Python: Replace characters at multiple index positions in a string with the same character

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)

Python: Replace characters at multiple index positions in a string with different characters

In the above example, we replace all the characters at given positions by the same replacement characters. But it might be possible that in some scenarios, we want to replace them with different replacement characters.
Suppose we have a dictionary that contains the index positions and the replacement characters as key-value pairs. We want to replace all the characters at these index positions by their corresponding replacement character. To do that, we will iterate over all the key-value pairs in the dictionary. And for each key, replace the character at that index position by the character in the value field. For example,

sample_str = "This is a sample string" char_to_replace = # Replace multiple characters with different replacement characters for index, replacement in char_to_replace.items(): sample_str = replace_char_at_index(sample_str, index, replacement) print(sample_str)

We can use the string slicing in python to replace the characters in a string by their index positions.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

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('') 

strings are immutable, you'd need to create a new string. It would be of the form slice_before_index + char + slice_after_index .

5 Answers 5

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:] 
replacer("mystring", "12", 4) 'myst12ing' 

Источник

Оцените статью