簡體   English   中英

從字符串中刪除反斜杠字符

[英]Remove backslash character from string

我有一個文件,其中包含美國的每個郵政編碼以及其各自的緯度和經度。 文件格式為“ 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)

做這個:

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

輸出:

['00602', '18.361945', '-67.175597']

您的代碼:

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

暫無
暫無

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

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