0

I've been trying for hours to do this in Python and I don't know what else to do. I have a string similar to this:

title = "Marielizabeth's Diary Chapter 9"

I want to get the number after the word "chapter" and then put a 0 in front of it: "Marielizabeth's Diary Chapter 09". I can't use title.replace because I don't know what I'll get. I only know that the number is after the word "chapter".

chapter = title.split('Chapter ', 1)
for char in chapter:
 print char

But it doesn't work. How can I do this?

Final solution:

title = "Marielizabeth's Diary Chapter 9"
re.sub('Chapter (\d$)', lambda m: "0" + m.group(1), title)

2 Answers 2

2

If your problem statement is 100% accurate, there is a very simple way, use the replace method and replace "Chapter " with "Chapter 0"

e.g.

title = "Marielizabeth's Diary Chapter 9"
title = title.replace("Chapter ", "Chapter 0")

This depends upon a single space between chapter and the following number, i.e., an exact match to your problem statement.

Sign up to request clarification or add additional context in comments.

10 Comments

"I can't use title.replace because I don't know what I'll get." -OP
This is a nice answer, though still not sure if Chapter 10 should be replaced with Chapter 010. Probably the OP wants to "catch" a single digit only.
Thanks to everyone for their answers! Yes, I need to replace it only if it's single digit.
Yes, I answered this after the regex based answer by you (alecxa) was already posted -- a certainly more general approach. It is just that clever use of replace can be an incredibly simple and fast solution sometimes that people overlook because regex is potent. Problem definition is definitely the key to writing the correct solution.
@GaryWalker yeah, seeing a bigger picture :)
|
1

You can pass a function inside the repl argument of re.sub():

>>> import re
>>> title = "Marielizabeth's Diary Chapter 9"
>>> re.sub('Chapter (\d)', lambda m: "0" + m.group(1), title)
"Marielizabeth's Diary 09"

Here (\d) is a capturing group that matches a single digit.

2 Comments

You don't necessarily need the (\d+) instead of (\d). Both will match "Chapter 9"
@MartinKonecny yup, wasn't sure about whether match one or multiple digits, let's see what the OP would say. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.