Diltopagalhaibluraytorrentdownload I want to replace the word "torrent" with "djl" but I have difficulties to find a string replacement as the string is not the same at the first and the last word. I can do it by writing a loop: diltopagalhaibluraytorrentdownload str1 = 'diltopagalhaibluraytorrentdownload' str2 = 'torrentdownload' replaced = str1.replace('torrent', 'djl') print(replaced) However I would like to use the regular expression like: replaced = re.sub(pattern, newstring, pattern) I tried to use \w+\b\w+ but it didn't work. Can anyone help please? Thanks in advance. A: As I understand you want to replace 'torrent' with 'djl' in any word, then use this: import re str1 = 'diltopagalhaibluraytorrentdownload' replaced = re.sub('\w+\b\w+', 'djl', str1) print(replaced) Output: djlhalibdljallbitilbmuarjbtixdalbrbixtriubrk Use the regular expression in re module to replace the word 'torrent' with 'djl'. The re.sub method can replace all instances of a pattern in a string. Patterns are sequences of characters that indicate the strings that should be replaced. Patterns may contain any characters except for the following special ones: '^' Matches the beginning of the string. '$' Matches the end of the string. '\ ' Matches any single character in the string. '\(\)' Matches a set of characters enclosed in ( and ). '\1' Matches whatever was matched by the first parenthesized subexpression in the pattern. '\1' Matches whatever was matched by the first parenthesized subexpression in the pattern. [Self-effic 595f342e71
Related links:
Comments