V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
rogwan
V2EX  ›  Python

为什么有“空格”隔断的字符串, split 切分后取不到值?

  •  
  •   rogwan · Dec 26, 2015 · 3675 views
    This topic created in 3787 days ago, the information mentioned may be changed or developed.

    根据用户的访问 ip 回显用户的城市名称:

    ip = request.remote_addr
    city_name = str(find(ip))

    这样 ip 地址库返回的 city_name 名称是“中国 湖南 长沙”,“中国 北京 北京”这样的结构;如果 ip 库找不到对应的城市名称就会显示“中国 福建”。
    我不要显示这么长的名称,只要显示“长沙”、“北京”、“福建”这样最后一个的位置即可,修改如下( python):

    city_name = str(find(ip)).split(' ').pop(-1)

    但是取不到“长沙”、“北京”、“福建”这样的值,是怎么回事呢?

    8 replies    2015-12-27 15:35:40 +08:00
    Allianzcortex
        1
    Allianzcortex  
       Dec 26, 2015
    环境限制,没法验证:

    * 用 str(find(ip)).split('')[-1]

    * 用 *_,city_name=str(find(ip))
    sagnitude
        2
    sagnitude  
       Dec 26, 2015
    把你这句话里面调用任何一个函数的结果,都 print 出来,自己看看
    另外, whitespace character 和空格是不一样的
    这种问题还请自己搜索,别人回答了和自己找到答案是不一样的,自己找到的答案记得更牢
    momo1999
        3
    momo1999  
       Dec 26, 2015
    我猜是\t
    greatghoul
        4
    greatghoul  
       Dec 26, 2015 via Android
    为 \s+ 吧
    greatghoul
        5
    greatghoul  
       Dec 26, 2015 via Android
    另外,别忘了还有个中文的空格
    akagi
        6
    akagi  
       Dec 26, 2015
    rogwan
        7
    rogwan  
    OP
       Dec 26, 2015
    谢谢大家的建议,试了不行,我再看下返回的结果是什么格式的值
    wgwang
        8
    wgwang  
       Dec 27, 2015
    空格看下是什么字符吧, 有可能是 web 的  也有可能是全角空格等。

    特别是中文,从网上抓取下来的,要十分注意全角字符(包括全角空格,全角标点符号,比如逗号等)。

    偶们招 python 工程师,做美股金融的,有兴趣的找我聊聊啊。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5385 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 08:05 · PVG 16:05 · LAX 01:05 · JFK 04:05
    ♥ Do have faith in what you're doing.