#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.
0:03 This video will show you advanced string replacing
0:06 using re.sub.
0:08 For example, we have a string here
0:09 on doing the 100 days of code, 200 days of Django,
0:12 and, of course, 365 days of PyBites.
0:16 So you're doing a simple string replacement.
0:20 It's a bit ugly, right.
0:22 So this will work but.
0:25 When you start to do things multiple times,
0:28 you have to think about a better way to do it.
0:31 So let's use re.sub
0:34 to make a more flexible replacement regex.
0:38 So re.sub...
0:40 raw string
0:42 and I want one or more digits
0:44 and I just want to replace those by 100.
0:48 And I do that on the text
0:50 and this works as well and it's more flexible
0:54 because if there are will be like five or six
0:57 of these hashtags with different integers,
1:00 they all would work.
1:03 Now let's look at a more advanced example
1:07 where we also want to capture the thing we replaced.
1:12 Say, for the same string,
1:14 I want to replace the thing after the days off.
1:17 So all should be Python, but we want to respect the integer
1:21 so I want to have 100 days of Python,
1:23 200 days of Python, and 365 days of Python.
1:26 Doesn't really make sense in a sentence
1:28 but it does for our exercise.
1:30 And the way to do that is to write a re.sub...
1:35 raw string.
1:37 And let's define the regular expression as a literal hash.
1:45 One or more digits.
1:47 Hard-code days of
1:51 one or more alphanumeric characters.
1:55 Here, you see these capturing parenthesis again.
2:00 I'm going to use that in a replacement part
2:02 which is the second argument
2:04 and I can reference that with backslash one.
2:08 So what this does is it takes the...
2:12 match of hashtag...
2:15 digits days off
2:17 and I'm going to put that in the replacement string.
2:21 And then I want to hard-code Python
2:25 and I want to do this on text.
2:28 And there you go.
2:29 Awesome, I'm doing 100 days of Python, 200 days of Python,
2:33 and, of course, 365 days of Python.
2:35 That's a wrap.
2:37 I hope you enjoyed this and got a better feeling
2:40 of how to write your regexes in Python.
2:44 Of course it's not a complete list of all the features
2:47 and that's why in day two I will provide you
2:50 some more resources and things you can check out.