从字符串中删除反斜杠字符

时间:2018-08-07 03:44:09

标签: python string python-3.x

我有一个文件,其中包含美国的每个邮政编码以及它们各自的纬度和经度。文件格式为“ ZIP / LAT / LNG \ n”,我将每个值保存到数据库中。因此,我编写了以下代码来测试是否可以正确拆分值:

zip_code_file = open('zipcode.rtf')
for s in zip_code_file.read().split(','):
    print(s)

但此打印 “ 00602” “ 18.361945”  “ -67.175597 \”

如何从经度中删除该“ \”,以便将其正确保存到数据库中?我尝试了以下操作,但没有成功:

for s in zip_code_file.read():
    if s == '\\':
        s.replace('\]', '')
    print(s)

2 个答案:

答案 0 :(得分:0)

执行以下操作:

and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'))

输出:

l=["00602", "18.361945", "-67.175597\\"]
print([i.replace('\\','') for i in l])

答案 1 :(得分:0)

您的代码:

for s in zip_code_file.read(): # ok, you get lines
    if s == '\\':              # if the whole line is equal to \
        s.replace('\]', '')    # replace "\]" (???) with ""
    print(s)

问题:

  1. 您的if条件仅在整个字符串为\
  2. 时有效
  3. str.replace()确实返回了您不留用的更改字符串,因此将其丢弃

解决方案:

with open('zipcode.rtf') as zip_code_file:
    lines = zip_code_file.readlines()

lines = [x.strip() for x in lines if x.strip()] # removes whitespaces && empty lines

for l in lines:
    try:
        zipCode,lat,long = l.split(",")  # split on ',' or '/'? your code and Q differ
        long = long.rstrip("\\") # remove trailing \

        # do smth with zipCode,lat,long

    except ValueError as ve:
        print("Value error in line: ", l)