在变量中搜索不同的字符串长度

时间:2015-10-06 10:55:23

标签: python

对于可变的phoneNumber,它要求输入整个电话号码;像这样的东西:029 123456.但是,我只需要第一个区号。但是也可以有像这样的区号:01845 123456,区号不同的字符数。我如何获得它只是将区号存储在变量中?

这是this的一小部分样本:

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()

1 个答案:

答案 0 :(得分:0)

让用户单独输入区号,然后输入数字,或者让他们输入区号,然后输入空格,然后输入数字并分开:

单独:

area = raw_input("Enter your area code: ")
num = raw_input("Enter you phone number: ")


import csv

r = csv.reader(open("phonecodes.csv"))
for ph_cde, ar_cde, ex, lat, lon in r:
    if "0" + ph_cde ==  area:
       ........

分裂:

area, num = raw_input("Enter your phone number (UK landline only) in format 

AREA NUM:").split()


import csv

r = csv.reader(open("phonecodes.csv"))
for ph_cde, ar_cde, ex, lat, lon in r:
   if "0" + ph_cde ==  area:
        .........

您的数据以逗号分隔,因此csv模块将拆分为您的列。我也使用raw_input作为你的print语句建议你使用的是python2而不是python3。