Python replace string in line

Метод replace() в Python

Метод replace() возвращает копию строки, в которой все вхождения подстроки заменяются другой подстрокой.

Параметры

Метод в Python может принимать максимум 3 параметра:

  • old ‒ старая подстрока, которую нужно заменить;
  • new ‒ новая подстрока, которая заменит старую подстроку;
  • count (необязательно) ‒ сколько раз вы хотите заменить старую подстроку новой.

Примечание: Если число не указано, метод заменяет все вхождения старой подстроки новой.

Возвращаемое значение

Команда возвращает копию строки, в которой старая подстрока заменяется новой подстрокой. Исходная строка не изменилась.

Если старая подстрока не найдена, возвращается копия исходной строки.

Пример 1: Использование команды

song = 'cold, cold heart' # replacing 'cold' with 'hurt' print(song.replace('cold', 'hurt')) song = 'Let it be, let it be, let it be, let it be' # replacing only two occurences of 'let' print(song.replace('let', "don't let", 2))
hurt, hurt heart Let it be, don't let it be, don't let it be, let it be

Дополнительные примеры

song = 'cold, cold heart' replaced_song = song.replace('o', 'e') # The original string is unchanged print('Original string:', song) print('Replaced string:', replaced_song) song = 'let it be, let it be, let it be' # maximum of 0 substring is replaced # returns copy of the original string print(song.replace('let', 'so', 0))
Original string: cold, cold heart Replaced string: celd, celd heart let it be, let it be, let it be

Источник

Python – How to Replace String in File?

To replace a string in File using Python, follow these steps:

  1. Open input file in read mode and handle it in text mode.
  2. Open output file in write mode and handle it in text mode.
  3. For each line read from input file, replace the string and write to output file.
  4. Close both input and output files.
Читайте также:  Таблица

Examples

1. Replace a string in File

Consider that we have a text file with some spelling mistakes. And we have found that the string python is mis-spelled as pyton in the file.

In the following example, we will replace the string pyton with python in data.txt file, and write the result to out.txt.

Python Program

#input file fin = open("data.txt", "rt") #output file to write the result to fout = open("out.txt", "wt") #for each line in the input file for line in fin: #read replace the string and write to output file fout.write(line.replace('pyton', 'python')) #close input and output files fin.close() fout.close()
  1. Open data.txt in read text rt mode and get the reference to fin.
  2. Open out.txt in write text wt mode and get the reference to fout.
  3. for line in fin :for each line in fin i.e., data.txt, line.replace(): replaces string pyton with python and fout.write: writes to out.txt.
  4. fin.close(): closes the file referenced by fin, fout.close(): closes the file referenced by fout.
Welcome to www.pytonexamples.org. Here, you will find pyton programs for all general use cases.

Output File

Welcome to www.pythonexamples.org. Here, you will find python programs for all general use cases.

The string pyton in the file is replaced with the string python.

2. Replace string and update the original file

In the following example, we will replace the string pyton with python in data.txt file, and overwrite the data.txt file with the replaced text.

Python Prgoram

#read input file fin = open("data.txt", "rt") #read file contents to string data = fin.read() #replace all occurrences of the required string data = data.replace('pyton', 'python') #close the input file fin.close() #open the input file in write mode fin = open("data.txt", "wt") #overrite the input file with the resulting data fin.write(data) #close the file fin.close() 
  1. Open file data.txt in read text mode rt.
  2. fin.read() reads whole text in data.txt to the variable data.
  3. data.replace() replaces all the occurrences of pyton with python in the whole text.
  4. fin.close() closes the input file data.txt.
  5. In the last three lines, we are opening data.txt in write text wt mode and writing the data to data.txt in replace mode. Finally closing the file data.txt.
Welcome to www.pytonexamples.org. Here, you will find pyton programs for all general use cases.

The same input file after program execution.

Welcome to www.pythonexamples.org. Here, you will find python programs for all general use cases.

Summary

In this tutorial of Python Examples, we learned to replace a string with other in file, with help of well detailed examples.

Источник

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