2

How do I use the re.sub python method to append +1 to a phone number?

When I use the following function it changes this string "802-867-5309" to this string "+1+15309". I'm trying to get this string "+1-802-867-5309". The examples in the docs replace show how to replace the entire string I don't want to replace the entire string just append a +1

import re
def transform_record(record):
  new_record = re.sub("[0-9]+-","+1", record)
  return new_record

print(transform_record("Some sample text 802-867-5309 some more sample text here"))
Paolo
  • 21,270
  • 6
  • 38
  • 69
larry8989
  • 339
  • 1
  • 11

2 Answers2

4

If you can match your phone numbers with a pattern you may refer to the match value using \g<0> backreference in the replacement.

So, taking the simplest pattern like \d+-\d+-\d+ that matches your phone number, you may use

new_record = re.sub(r"\d+-\d+-\d+", r"+1-\g<0>", record)

See the regex demo. See more ideas on how to match phone numbers at Find phone numbers in python script.

See the Python demo:

import re
def transform_record(record):
  new_record = re.sub(r"\d+-\d+-\d+", r"+1-\g<0>", record)
  return new_record

print(transform_record("Some sample text 802-867-5309 some more sample text here"))
# => Some sample text +1-802-867-5309 some more sample text here
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • just wanna add a comment to the verified answer the regex should be r"\d+-\d+-?\d+", r"+1-\g<0>" question mark nezt to the second dash , so that even if the number only have one dash like for instance 802-8675309 it will still print +1-802-867-5309 the final code is : new_record = re.sub(r"\d+-\d+-?\d+", r"+1-\g<0>", record) – Fredybec Aug 04 '22 at 20:14
0

You can try this:

new_record = re.sub(r"\d+-[\d+-]+", r"+1-\g<0>", record)
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 30 '23 at 12:17