【问题标题】:Adding characters to a string in python 3在python 3中向字符串添加字符
【发布时间】:2011-03-08 21:13:11
【问题描述】:

我目前有一个字符串,我想通过在每个字符之间添加空格来编辑它,所以我目前有s = 'abcdefg',我希望它变成s = 'a b c d e f g'。有没有简单的方法可以使用循环来做到这一点?

【问题讨论】:

    标签: python string python-3.x


    【解决方案1】:
    >>> ' '.join('abcdefg')
    'a b c d e f g'
    

    【讨论】:

    • 删除函数调用中不需要的空格。
    • @Jakob Bowyer:呃,为什么?上次我检查时,空格的使用是用户选择的编码风格..
    • Pep8 Avoid extraneous whitespace in the following situations: - Immediately inside parentheses, brackets or braces. Yes: spam(ham[1], {eggs: 2}) No: spam( ham[ 1 ], { eggs: 2 } )
    • @Jakob Bowyer:PEP8 不是规则或每个人都必须遵循的东西,它是一个指导方针。如果开发人员想在他们的项目中使用不同的样式(当 Python 不是他们所做的全部时,这尤其有意义),那完全没问题,PEP8 应该被忽略而不是盲目地强制执行。
    • @Jakob:如果您建议进行风格清理而不是直截了当地告诉人们该做什么,您会得到更好的接待。我不认为@Lennart 应该在其他人的答案中做出改变。
    【解决方案2】:

    您确实指定了“使用循环”

    Python 中的字符串是可迭代的,这意味着您可以对其进行循环。

    使用循环:

    >>> s = 'abcdefg'
    >>> s2=''
    >>> for c in s:
    ...    s2+=c+' '
    >>> s2
    'a b c d e f g '    #note the trailing space there...
    

    使用推导式,您可以生成一个列表:

    >>> [e+' ' for e in s]
    ['a ', 'b ', 'c ', 'd ', 'e ', 'f ', 'g ']  #note the undesired trailing space...
    

    你可以使用map:

    >>> import operator
    >>> map(operator.concat,s,' '*len(s))
    ['a ', 'b ', 'c ', 'd ', 'e ', 'f ', 'g ']
    

    然后你有那个讨厌的列表而不是一个字符串和一个尾随空格......

    你可以使用正则表达式:

    >>> import re
    >>> re.sub(r'(.)',r'\1 ',s)
    'a b c d e f g '
    

    您甚至可以使用正则表达式修复尾随空格:

    >>> re.sub(r'(.(?!$))',r'\1 ',s)
    'a b c d e f g'
    

    如果你有一个列表,使用join 产生一个字符串:

    >>> ''.join([e+' ' for e in s])
    'a b c d e f g '
    

    您可以使用string.rstrip() 字符串方法来删除不需要的尾随空格:

    >>> ''.join([e+' ' for e in s]).rstrip()
    'a b c d e f g'
    

    您甚至可以写入内存缓冲区并获取字符串:

    >>> from cStringIO import StringIO
    >>> fp=StringIO()
    >>> for c in s:
    ...    st=c+' '
    ...    fp.write(st)
    ... 
    >>> fp.getvalue().rstrip()
    'a b c d e f g'
    

    但由于join 可用于列表或可迭代对象,您不妨在字符串上使用连接:

    >>> ' '.join('abcdefg')
    'a b c d e f g'   # no trailing space, simple!
    

    以这种方式使用join是最重要的Python习语之一。

    使用它。

    还有性能方面的考虑。阅读this comparison,了解 Python 中的各种字符串连接方法。

    【讨论】:

      【解决方案3】:

      使用 f 字符串,

      s = 'abcdefg'
      temp = ""
      
      for i in s:
          temp += f'{i} '
          
      s = temp   
      print(s)
      
      a b c d e f g
      
      [Program finished]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-28
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 2011-04-29
        • 2017-11-04
        • 2017-06-25
        • 1970-01-01
        相关资源
        最近更新 更多