2

Here's a very dummy example of what I'm trying to accomplish, input is text:

{placeholder}, John Jones\n{placeholder}, Ben Franklin\n{placeholder}, George Washington

What I want to do is replace every instance of {placeholder} with the output of a function using data from the same line, e.g. the first initial and last name (would need to input first and last name to a function).

def initializer(name):
    return f"{name.split(' ')[0][0]}. {name.split(' ')[1]}"

The desired result would be:

J. Jones, John Jones\nB. Franklin, Ben Franklin\nG. Washington, George Washington
1
  • is your input "{placeholder}, John Jones\n{placeholder}, Ben Franklin\n{placeholder}, George Washington"? or do you have the names in a list? Commented Sep 24, 2019 at 19:19

2 Answers 2

1

A regular expression with a replacement function would work:

import re

s = "{placeholder}, John Jones\n{placeholder}, Ben Franklin\n{placeholder}, George Washington"

def repl_function(m):
    return "{}. {}, {} {}".format(m.group(1)[0],m.group(2),m.group(1),m.group(2))

print(re.sub("\{placeholder},\s+(.*?)\s(.*)",repl_function,s))

prints:

J. Jones, John Jones
B. Franklin, Ben Franklin
G. Washington, George Washington

How does it work?

It captures {placeholder} and 2 words (until end of line, not matched by .* because re.DOTALL is not set and creates 2 groups (2 name parts).

On match, it calls the repl_function replacement function with the match object (second parameter of re.sub can be a string, a bytes object or a function which accepts one argument: the match object).

Just return the reformatted match object as string by shortening the first name and repeating the other information (this can be done in a lambda as well, but it's maybe more readable as a real function)

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

1 Comment

This is exactly what I was looking for, wasn't sure how to go about using re.sub like this
1

The following will work assuming you are using Python >= 3.6:

# it is the same function you showed in your question
def initializer(name):
    return f"{name.split(' ')[0][0]}. {name.split(' ')[1]}"

s = '{placeholder}, John Jones\n{placeholder}, Ben Franklin\n{placeholder}, George Washington'
names = [name.rstrip() for name in s.split('{placeholder}, ') if name != '']
output = '\n'.join(f'{initializer(name)}, {name}' for name in names)

Output

'J. Jones, John Jones\nB. Franklin, Ben Franklin\nG. Washington, George Washington'

Comments

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.