Skip to content
Advertisement

How to use .join() and .format() together in python

I am trying to use .join() and .format() together in the same loop, but unable to do so.

Sample Data:

somelist = [[{'web': 'www.example.com'}], [{'web': 'http://www.example.com/content/vb'}, {'123.123.3968 ': 'tel:123.123.3968'}], [{'web': 'https://example.com/fsdds/'}, {'': 'mailto:abc.xyz@ddaa.com?subject=Inquiry from abc.com%20'}], [{'web': 'https://example.com/svsd'}, {'web': 'http://example.com/vsdv'}, {'098.765.4321 ': 'tel:098.765.4321'}, {'B': 'mailto:xssc.xyz@ddaa.com?subject=Inquiry from xyz.com'}]]

Filtering out phone number as below:

phn = []
for lst in somelist:
    ph_check = []
    for ph in lst:
        ph_check += [val for val in ph.values() if re.match(r'tel:(?(d{3}))?[^d]*(d{3})[^d]*(d{4})', val)]
    phn.append(', '.join(ph_check) if ph_check else '')

I want to format the phone number in the below format, can anyone suggest me how to pass the below format:

"{} {} {}".format(ph_check.group(1), ph_check.group(2), ph_check.group(3))

Getting output as: tel:123.456.7890

But I want the output as: 123 456 7890

Advertisement

Answer

phone_nr = "tel:123.456.7890"
phone_nr[4:].replace('.', ' ')

Result:

123 456 7890

This makes:

import re

somelist = [[{'web': 'www.example.com'}], [{'web': 'http://www.example.com/content/vb'}, {'123.123.3968 ': 'tel:123.123.3968'}], [{'web': 'https://example.com/fsdds/'}], [{'web': 'https://example.com/svsd'}, {'web': 'http://example.com/vsdv'}, {'098.765.4321 ': 'tel:098.765.4321'}]]

phn = []
for lst in somelist:
    ph_check = []
    for ph in lst:
        ph_check += [val for val in ph.values() if re.match(r'tel:(?(d{3}))?[^d]*(d{3})[^d]*(d{4})', val)]
    phn.append(', '.join(ph_check)[4:].replace('.', ' ') if ph_check else '')
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement