[英]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)
问题:
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.