Appending To A Line
I have a certain string
fruits as such:
Apples Bananas Pineapples
There is a carriage return
\r at the end of each line, as well as at the beginning and end of the string. Using RegEx, how would I go about appending
: 1 to the end of the first line
Apples? I have tried the following to no avail:
re.sub("Apples(\r)", "\1:1", fruits)
My thinking was that
\1 should replace what's in the brackets
(\r), however everything in the pattern is being replaced.
What you are doing is matching
"Apples\r", capturing the
"\r" in the process, and then replacing the entire match with
For this simple example, there's no need to capture matches to
\r, anyway, since the only thing that will match it is
\r. You can hard code that into the replacement string.
I'll assume you want the resulting string to be
You can use a lookbehind so that
Apples is not consumed (though I hear that consuming one a day keeps the doctor away):
re.sub("(?<=Apples)\r", ": 1\r", fruits)
But you could also just do:
re.sub("Apples\r", "Apples: 1\r", fruits)
The lookbehind would be more useful if you wanted to add
: 1 after each fruit:
re.sub("(?<=[^\r])\r", ": 1\r", fruits)
The above says find every
\r that follows a character that isn't an
\r, and replace them with
: 1\r. The result would then be:
# \rApples: 1\rBananas: 1\rPineapples: 1\r\r
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module