menu
techminis

A naukri.com initiative

google-web-stories
Home

>

Programming News

>

How to Rep...
source image

RealPython

1M

read

266

img
dot

Image Credit: RealPython

How to Replace a String in Python

  • Replacing strings in Python is a fundamental skill. You can use the .replace() method for straightforward replacements, while re.sub() allows for more advanced pattern matching and replacement.
  • You can replace parts of a string by chaining .replace() calls or using regex patterns with re.sub().
  • You replace a letter in a string by specifying it as the first argument in .replace().
  • You remove part of a string by replacing it with an empty string using .replace() or re.sub().
  • You replace all occurrences of substrings in a string by using .replace().
  • In this tutorial, you’ll work with a chat transcript to remove or replace sensitive information and unwanted words with emojis. To achieve this, you’ll use both direct replacement methods and more advanced regular expressions.
  • You’ll be playing the role of a developer for a company that provides technical support through a one-to-one text chat. You’re tasked with creating a script that’ll sanitize the chat, removing any personal data and replacing any swear words with emojis.
  • The first thing you’ll want to do is to take care of any swear words.
  • As you can see, you can chain .replace() onto any string and provide the method with two arguments. The first is the string that you want to replace, and the second is the replacement.
  • But there’s another swear word that’s not getting replaced because in Python, the string needs to match exactly.

Read Full Article

like

16 Likes

For uninterrupted reading, download the app