#100DaysOfCode in Python Transcripts
Chapter: Days 28-30: Regular Expressions
Lecture: Using re.sub for string replacing

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Welcome back to the last section on the regex lesson. This video will show you advanced string replacing using re.sub.
0:09 For example, we have a string here on doing the 100 days of code, 200 days of Django, and, of course, 365 days of PyBites.
0:17 So you're doing a simple string replacement. It's a bit ugly, right. So this will work but. When you start to do things multiple times,
0:29 you have to think about a better way to do it. So let's use re.sub to make a more flexible replacement regex. So re.sub... raw string
0:43 and I want one or more digits and I just want to replace those by 100. And I do that on the text and this works as well and it's more flexible
0:55 because if there are will be like five or six of these hashtags with different integers, they all would work. Now let's look at a more advanced example
1:08 where we also want to capture the thing we replaced. Say, for the same string, I want to replace the thing after the days off.
1:18 So all should be Python, but we want to respect the integer so I want to have 100 days of Python, 200 days of Python, and 365 days of Python.
1:27 Doesn't really make sense in a sentence but it does for our exercise. And the way to do that is to write a re.sub... raw string.
1:38 And let's define the regular expression as a literal hash. One or more digits. Hard-code days of one or more alphanumeric characters.
1:56 Here, you see these capturing parenthesis again. I'm going to use that in a replacement part which is the second argument
2:05 and I can reference that with backslash one. So what this does is it takes the... match of hashtag... digits days off
2:18 and I'm going to put that in the replacement string. And then I want to hard-code Python and I want to do this on text. And there you go.
2:30 Awesome, I'm doing 100 days of Python, 200 days of Python, and, of course, 365 days of Python. That's a wrap.
2:38 I hope you enjoyed this and got a better feeling of how to write your regexes in Python. Of course it's not a complete list of all the features
2:48 and that's why in day two I will provide you some more resources and things you can check out.


Talk Python's Mastodon Michael Kennedy's Mastodon