对于可变电话号码,它要求输入整个电话号码;像这样:029 123456.然而,我只需要第一个区号。但也可以有这样的区号:01845 123456与区号的字符数量不同。我如何得到它,所以它只是将区号存储在变量中?在变量中搜索不同的字符串长度
这里的full CSV file的小样本:
PhoneCode,Area,Example,Latitude,Longitude
113,Leeds,(0113) xxx xxxx,53.801279,-1.548567
114,Sheffield,(0114) xxx xxxx,53.381129,-1.470085
115,Nottingham,(0115) xxx xxxx,52.95477,-1.158086
116,Leicester,(0116) xxx xxxx,52.636878,-1.139759
117,Bristol,(0117) xxx xxxx,51.454513,-2.58791
118,Reading,(0118) xxx xxxx,51.452884,-0.973906
1200,Clitheroe,(01200) xxxxxx,53.871098,-2.393083
1202,Bournemouth,(01202) xxxxxx,50.719164,-1.880769
1204,Bolton,(01204) xxxxxx,53.584441,-2.428619
,这里是我的代码至今:
phoneNumber = input("Enter your phone number (UK landline only):")
file = open("phonecodes.csv","r")
#Complete the code here
for line in file:
data = line.split(",")
areaCode = data[0]
if phoneNumber == "0" + areaCode:
print data[1]
file.close()
他们都在单独的列中,所以只需提取所需的列,使用csv模块 –
两个注释:1)不要使用'file'作为变量名称;使用内建的变量名是一个坏主意。 2)'f = open(path)... f.close()'设计是一个反模式;更好地使用'与开放(路径)为f:...',这确保文件将始终关闭。 – alexwlchan
@Padraic坎宁安谢谢,但这不是我问的。我问的是如何从phoneNumber中存储区号,而不是整个号码。所以,而不是存储029 123456,它只是存储029. – ConorYoungs