简体   繁体   中英

Remove backslash character from string

I have a file with every zip code in the US and its respective latitude and longitude. The file format is "ZIP/LAT/LNG\\n" I am going to save each of those values to a database. So I wrote the following code to test if I could properly split the values:

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

But this prints "00602" "18.361945" "-67.175597\\"

How can I remove that '\\' from the longitude so I can properly save the number to my database? I tried the following, but it did not work:

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

Do this:

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

Output:

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

Your code:

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)

Problem:

  1. your if condition only works if the whole string is \\
  2. str.replace() does return a changed string that you do not keep around, so its discarded

Solution:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM