r/codereview • • Sep 24 '20

Python Any way I can make this simple code simpler?

Post image
25 Upvotes

10 comments sorted by

3

u/Strawberry_Gene Sep 24 '20

intended goal: input= Lebron, James; Drew, Brees output= J. Lebron, B. Drees

3

u/[deleted] Sep 25 '20
def format_names(names):
  """Returns a list of formatted names"""

  names = names.split("; ")

  formatted_names = []

  for name in names:
    first_name, last_name = name.split(", ")
    formatted_names.append(f"{last_name[0]}.{first_name}")

  return ", ".join(formatted_names)

if __name__ == "__main__":
  names = input()

  print(format_names(names))

I think this can solve your problem.

2

u/sirk390 Sep 25 '20

Your code is hard to read because it is low level. I would create an object such that the business logic can be at a high level. (nb: My code would need to be improved because it is not doing any error verification. )

class PersonName()
    def __init__(firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname
    
    @classmethod 
    def parse(cls, text):
        return cls(*text.split(", "))
    
    def shortname(self):
        return (self.firstname[0] + ". " + self.lastname)
    
persons =  [PersonName.parse(name) for name in split("; ")]
print ([person.shortname() for person in persons]

-1

u/brianjenkins94 Sep 25 '20 edited Sep 25 '20

Not sure that I would necessarily suggest doing it this way, but another option to consider:

const output = [];

for (const element of "Lebron, James; Drew, Brees".split("; ")) {
    output.push(element.replace(/(\w+), (\w)\w+/g, function(...matches) {
        return matches[2] + ". " + matches[1];
    }));
}

console.log(output.join(", "));

I'm not familiar with how regexs are done in Python, but I have to imagine they're more straight-forward.

12

u/[deleted] Sep 25 '20

[removed] — view removed comment

3

u/Strawberry_Gene Sep 25 '20

What are the f'' and {} called? Haven't learned about those yet.

6

u/[deleted] Sep 25 '20

They are formally called f strings within Python. They are more performant and more Pythonic so I suggest you use them more and more in your Python code.

5

u/slipperier_slope Sep 25 '20

String interpolation

2

u/Buxsle Sep 25 '20

It's a way of writing ("string" + variable + "string" ) in a more readable way.