Replace Character in String at Index in Python
As we all know, strings in Python are immutable, so there is no possible way of directly making changes to the string during the runtime of the Python code. However, there is a need for doing this in some cases, and it can be done indirectly in different ways.
This tutorial demonstrates how to replace a character in a string at a specific index in Python.
Use String Slicing to Replace a Character in a String at a Certain Index in Python
List slicing is an efficient way to solve some of the problems encountered during the coding process. The colon ( : ) operator is utilized for the list slicing process. The details or parameters such as start , finish , and step can be specified with the help of the colon operator.
The following code uses string slicing to replace a character in a string at a certain index in Python.
The above code provides the following output:
Explanation:
- To replace a single character at the specified position in the given string, three sections are made by splitting the given string.
- The middle section contains only the character that needs to be replaced. The first and last sections contain the characters before and after the selected character, respectively.
- All three sections are then joined together using the simple + operator. However, instead of the middle section containing the selected character, the character that needs to be replaced is joined in place of it.
Use a List to Replace a Character in a String at a Certain Index in Python
A list is one of the four built-in datatypes that Python provides, and it is utilized to stock several items in a single variable. Lists are ordered, changeable, and have a definite count.
In this method, the given string is first converted into a list. After that, the old character is replaced by the new character at the specified index. Finally, the list items are converted to a string using the join() function.
The following code uses a List to replace a character in a string at a certain index in Python.
The above code provides the following output:
These two were the methods that can be utilized to deal with a single character in a string. Moving on, we will now focus on replacing characters at multiple specified indices.
Replace More Than One Character at Different Indices With the Same Character in All the Cases
Here, we will make use of Lists. This method is utilized when there are a few indices, and all the characters at these multiple indices need to be replaced by a single character.
For this to work, all the indices in the given list would need to be iterated, and slicing can be implemented for replacing each found index that requires a character change.
The following code uses list slicing for when we need to replace characters at many indices with a single character.
The above code provides the following output:
Replace More Than One Character at Different Indices With Different Characters in All the Cases
In this case, the same character does not need to be replaced in all the indices.
For this purpose, we will make use of a dictionary instead of a list. A dictionary is much similar to a hashmap and stores the entered data in the form of key:value pairs.
In order to replace all the characters given in the selected indices with their respective replacement, iteration all over the created dictionary’s key:value pairs.
The following code replaces characters at multiple indices with their respective replacement.
The above code provides the following output:
Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.
Замена символа в строке по индексу в Python
Чтобы заменить символ заданным символом по указанному индексу, вы можете использовать нарезку строки в Python, как показано ниже:
Где, string – это новый символ, который необходимо заменить, а position – это индекс, по которому мы заменяем символ.
Пример 1: с помощью нарезки строки
В следующем примере мы возьмем строку и заменим символ с индексом 6 на e.
Пример 2: с помощью списка
В следующем примере мы возьмем строку и заменим символ с индексом 6 на e. Для этого мы сначала преобразуем строку в список, затем заменим элемент с заданным индексом новым символом, а затем присоединим элементы списка к строке.
В этом руководстве Python мы узнали, как заменить символ по определенному индексу в строке на новый символ.
Как заменить символ в строке по индексу?
Например: в строке AABAABAAАA нужно заменить именно 6й символ(по индексу 5) на A.
Строки в Python неизменяемы, поэтому для этой операции нет встроенного метода. Вам придётся создать новую строку на основе исходной.
Наиболее быстрый способ — взять срез до и после необходимого символа:
Ещё вы можете преобразовать строку к списку. Список изменяемый, и вы можете перезаписать один из его элементов, а затем преобразовать список обратно в строку:
Тип bytes — это неизменяемая последовательность байтов. Каждый элемент такой последовательности может хранить целое число от О до 255, обозначающее код символа. Этот тип поддерживает боль- шинство строковых методов, однако при доступе по индексу возвра- щается целое число, а не символ.
Тип bytearray — это изменяемая последовательность байтов. Данный тип аналогичен типу bytes, но вы можете изменять элементы такой строки по индексу. Также этот тип содержит дополнительные методы, которые позволяют добавлять и удалять элементы.
Взято из Справочник PYTHON. Кратко, быстро, под рукой | Дубовик Е. В., Кольцов Д. М.
Python String – Заменить символ в определенную позицию
Python – заменить символ по определенному индексу в строке
Чтобы заменить символ заданного символа в указанный индекс, вы можете использовать Slicing String Python, как показано ниже:
где персонаж Новый персонаж, который должен быть заменен на позиция Является ли индекс, на котором мы заменяем характер.
Пример 1: Замените символ в заданном положении в строке с помощью нарезки строки
В следующем примере мы возьмем строку, и замените символ на index = 6 с е Отказ
Пример 2. Замените символ в заданном положении в строке с использованием списка
В следующем примере мы возьмем строку, и замените символ на index = 6 с е Отказ Для этого мы сначала преобразуйте строку в список, затем замените элемент при заданном индексе с новым символом, а затем присоединитесь к элементам списка в String.
Резюме
В этом руководстве примеров Python мы узнали, как заменить символ по определенному индексу в строке с новым символом.