推荐学习书目
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
evolighting
V2EX  ›  Python

str().join()有没有像 str().split()那样能够给定一个分隔符参数,用这个分隔符连起来的方法呢?

  •  
  •   evolighting · May 22, 2015 · 4032 views
    This topic created in 4026 days ago, the information mentioned may be changed or developed.
    15 replies    2015-05-22 22:10:44 +08:00
    evolighting
        2
    evolighting  
    OP
       May 22, 2015
    @Septembers
    但是,join是不支持两个参数的呀?我也确实是在2.7版本的python上试过了
    结果:
    ”TypeError: join() takes exactly one argument (2 given)“
    Septembers
        3
    Septembers  
       May 22, 2015   ❤️ 1
    好吧看错了

    >>> '-'.join(str(_) for _ in range(10))
    '0-1-2-3-4-5-6-7-8-9'

    string.join只接受list of string

    see https://docs.python.org/2/library/string.html#string.join
    zhicheng
        4
    zhicheng  
       May 22, 2015 via Android
    你说的是什么?
    '-'.join(['a','b','c'])
    这样?
    evolighting
        5
    evolighting  
    OP
       May 22, 2015
    @zhicheng
    具体来说,就是把list中的东西连起来,用分隔符分隔一下...用于输出......类似与格式化输出吧,但是这个列表,一是非常长,二是长度不定....其实说起来应该还是可以用格式化输出的方法搞定的.....不过不太明白怎么做
    于是我用了一个愚蠢的方法解决这个问题,[x + "\t" for x in list] 这样.....
    来这里问问,其实纯粹就是好奇....搜来搜去没有找到很好答案...嗯我是新来的....
    evolighting
        6
    evolighting  
    OP
       May 22, 2015
    @Septembers
    原来如此,我并没有理解这个东西的用法多谢了!
    roychan
        7
    roychan  
       May 22, 2015
    >>> from functools import reduce
    >>> a = ['1', '2', '3']
    >>> b = reduce(lambda x, y: x + '-' + y, a)
    >>> b
    '1-2-3'
    >>>
    zhicheng
        8
    zhicheng  
       May 22, 2015 via Android
    赞楼上。。。。我决定把这题作为招聘笔试题。
    roychan
        9
    roychan  
       May 22, 2015
    @zhicheng 这方法比较麻烦…
    zhicheng
        10
    zhicheng  
       May 22, 2015 via Android
    哈哈哈,原来你不是在调侃。那么你没有Pass。。。
    roychan
        11
    roychan  
       May 22, 2015
    @zhicheng 才学了俩月=_=
    roychan
        12
    roychan  
       May 22, 2015
    @roychan 还是大一通识课学的 =_=
    sirgod
        13
    sirgod  
       May 22, 2015
    @roychan reduce不用import吧?直接用就行了
    zhyu
        14
    zhyu  
       May 22, 2015
    @sirgod python3
    staticor
        15
    staticor  
       May 22, 2015
    格式输出 pprint 有帮助吗?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1144 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 17:58 · PVG 01:58 · LAX 10:58 · JFK 13:58
    ♥ Do have faith in what you're doing.