簡體   English   中英

如何在python中的電話號碼列表中替換字符串?

[英]How to string replace in a list of phone numbers in python?

我在列表中有以下電話號碼:

+61 2 3456 2718
03 2756 2876
4567 8937 
+61 5 6573 8593
05 8583 7932

我想刪除第一個數字(如果為0),然后在每個數字中加上+61。 我怎樣才能做到這一點?

import re 
for i in phone:
    print(re.sub(r"(\+?\d{3})(\d{4})(\d+)", r"\1 \2 \3", i))
    re.sub('^\d+', '', i)

如果所有電話號碼均以0或某些國際代碼(例如+61 (或其他國際代碼)開頭,而您不需要任何其他檢查,則您的代碼可能很簡單(清晰):

fixed_phone_numbers = [f'+61{n[1:]}' if n[0] == '0' else n for n in phone_numbers]

如果出於某種原因,您想在Python 2中執行此操作:

fixed_phone_numbers = ['+61' + n[1:] if n[0] == '0' else n for n in phone_numbers]
phone = ["+61 2 3456 2718",
"03 2756 2876",
"4567 8937 ",
"+61 5 6573 8593",
"05 8583 7932"]
import re 
for i in phone:
    if(not i.startswith('+61')):
      if(re.match(r'^0', i)):
        i = re.sub('^0', '+61', i)
      else:
        i = '+61 ' + i
    print(i)

+61 2 3456 2718
+613 2756 2876
+61 4567 8937
+61 5 6573 8593
+615 8583 7932

您可以檢查第一個字符。如果它是'0',則用“ +61” +“ substring_of_phone_number_from_position_1”(i [1:])替換字符串。

import re 
for i in phone:
    if i[0]=='0':
        i='+61'+i[1:]
    elif i[0]!='+':
        i='+61'+i

希望能幫助到你 :-)。 我只用了正則表達式

In [1]: strings = """+61 2 3456 2718
   ...: 03 2756 2876
   ...: 4567 8937 
   ...: +61 5 6573 8593
   ...: 05 8583 7932"""
In [3]: import re

In [12]: for phoneno in strings.split('\n'):
    ...:     print(re.sub(r'^(0|\+61|)',r'+61',phoneno))
    ...:     
    ...:     

+61 2 3456 2718
+613 2756 2876
+614567 8937 
+61 5 6573 8593
+615 8583 7932

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM