Using python, in the following list I need to remove phone numbers which are repeated with country codes.
['(+44)45860787163','(+27)16345860787','45860787163','16345860787']
I tried using Cartesian product and 'in' operator to compare strings but nothing seems to be working. What I'd like to keep are the full phone numbers.
['(+44)45860787163','(+27)16345860787']
Using a regex you may extract the part you need, then using a dict, you can pair the number with its prefix (and avoid overwriting a prefix)
value = '(+44)45860787163,(+27)16345860787,45860787163,16345860787'
phones = {}
for phone, prefix, number in re.findall(r"((\(\+\d+\))?(\d+))", value):
if prefix != "" or number not in phone:
phones[number] = prefix
result = ",".join(v + k for k, v in phones.items())
print(result) # (+44)45860787163,(+27)16345860787
Using list comprehension
l = ['(+44)45860787163','(+27)16345860787','45860787163','16345860787']
l = [x for x in l if '(' in x]
print(l)
>>> ['(+44)45860787163', '(+27)16345860787']
If you want to be extra secure you can check for both semi colons
l = [x for x in l if '(' in x and ')' in x]
First of all, we get all the phone numbers. Then, we create a dictionary with number without extension as key and extension as value. If a number hasn't extension it's set to None. After, if we find the same number with extension None is replaced by the extension. At the end, we print the number with the corresponding extension.
numbers = '(+44)45860787163,(+27)16345860787,45860787163,16345860787'.split(',')
d = dict()
for number in numbers:
if ')' in number:
prefix, n = number.split(')')
prefix = prefix + ')'
else:
prefix = None
n = number
if n in d.keys():
if d[n] == None:
d[n] = prefix
else:
d[n] = prefix
print([k if v == None else v + k for k,v in d.items()])
You can use this solution:
number_string = '(+44)45860787163,(+27)16345860787,45860787163,16345860787'
result = []
for phone_number in number_string.split(','):
if "(" in phone_number:
result.append(phone_number)
print(result)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.