-1

Can anyone try to figure out how to fix this code:

import re
def rearrange_name(name):
  result = re.search(r"^(\w*), (\w*)$", name)
  if result == None:
    return name
  return "{} {}".format(result[2], result[1])

name=rearrange_name("Kennedy, John F.")
print(name)

it‘s supposed to output "John F., Kennedy"

Yilin Zuo
  • 11
  • 6

5 Answers5

3

As MYousefi pointed out, your regular expression isn't compatible with middle names. I found out the following using regex101:

  • \w matches any word character (equivalent to [a-zA-Z0-9_])

The string "John F." contains two characters what aren't word characters:

  • Space ( )
  • Dot (.)

Fixing your original regex would look like this (I would recommend + instead of *):

^(\w+), ([\w. ]+)$

To handle "double surnames", you have to allow spaces and hyphens in the first group:

^([\w -]+), ([\w. ]+)$

Alternate solution

It might be easier to solve your problem using str.split() and str.join() instead of using regex:

def rearrange_name(name):
    tokens = name.split(", ")
    return " ".join(reversed(tokens))

name=rearrange_name("Kennedy, John F.")
print(name)

This codes splits the name, re-arranges the two halves and joins them back together.

0

I already know how!

import re
def rearrange_name(name):
  result = re.search(r"^([\w \.-]*), ([\w \.-]*)$", name)
  if result == None:
    return name
  return "{} {}".format(result[2], result[1])

name=rearrange_name("Kennedy, John F.")
print(name)
Yilin Zuo
  • 11
  • 6
0

This is what I used and it worked.

import re
def rearrange_name(name):
  result = re.search(r"^(\w*), (.*)$", name)
  if result == None:
    return name
  return "{} {}".format(result[2], result[1])

name=rearrange_name("Kennedy, John F.")
print(name)
Peter9192
  • 2,899
  • 4
  • 15
  • 24
Ndiana
  • 1
  • 1
-1
import re
def rearrange_name(name):
  result = re.search(r"^(\w*), (\w*.*)$", name)
  if result == None:
    return name
  return "{} {}".format(result[2], result[1])

name=rearrange_name("Kennedy, John F.")
print(name)
ScottC
  • 3,941
  • 1
  • 6
  • 20
-2
import re
def rearrange_name(name):
  result = re.search(r"^(\w*), ([a-zA-Z]*.*)$", name)
  if result == None:
    return name
  return "{} {}".format(result[2], result[1])

name=rearrange_name("Kennedy, John F.")
print(name)
Thomas Kimber
  • 10,601
  • 3
  • 25
  • 42
  • 2
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 19 '22 at 07:30