【问题标题】:How can strings be concatenated?字符串如何连接?
【发布时间】:2011-02-12 06:51:01
【问题描述】:

如何在python中连接字符串?

例如:

Section = 'C_type'

将其与Sec_ 连接形成字符串:

Sec_C_type

【问题讨论】:

    标签: python string concatenation


    【解决方案1】:

    最简单的方法是

    Section = 'Sec_' + Section
    

    但为了效率,请参阅:https://waymoot.org/home/python_string/

    【讨论】:

    • 其实从你引用的那篇文章开始好像已经优化过了。通过 timeit 的快速测试,我无法重现结果。
    • OP 要求 Python 2.4 但关于 2.7 版,Hatem Nassrat 已经测试(2013 年 7 月)three concatenation techniques 其中+ 在连接少于 15 个字符串时更快,但他推荐其他技术:@ 987654325@和%。 (当前的评论只是为了确认上面@tonfa 的评论)。干杯;)
    • 如果你想要一个多行字符串连接会发生什么?
    • @pyCthon:嗯?您可以使用 \n 在字符串中添加换行符,也可以在 Python 中通过在行尾添加 \ 来续行。
    【解决方案2】:

    只是一个评论,因为有人可能会觉得它很有用 - 您可以一次连接多个字符串:

    >>> a='rabbit'
    >>> b='fox'
    >>> print '%s and %s' %(a,b)
    rabbit and fox
    

    【讨论】:

      【解决方案3】:

      更有效的连接字符串的方法是:

      加入():

      非常有效,但有点难以阅读。

      >>> Section = 'C_type'  
      >>> new_str = ''.join(['Sec_', Section]) # inserting a list of strings 
      >>> print new_str 
      >>> 'Sec_C_type'
      

      字符串格式:

      易于阅读,并且在大多数情况下比“+”连接更快

      >>> Section = 'C_type'
      >>> print 'Sec_%s' % Section
      >>> 'Sec_C_type'
      

      【讨论】:

      【解决方案4】:

      对于追加到现有字符串末尾的情况:

      string = "Sec_"
      string += "C_type"
      print(string)
      

      结果

      Sec_C_type
      

      【讨论】:

        【解决方案5】:

        你也可以这样做:

        section = "C_type"
        new_section = "Sec_%s" % section
        

        这不仅可以让您追加,还可以在字符串中的任何位置插入:

        section = "C_type"
        new_section = "Sec_%s_blah" % section
        

        【讨论】:

        • 此方法还允许您将 int 'concat' 到字符串,这不能直接使用 + 实现(需要将 int 包装在 str() 中)
        【解决方案6】:

        使用+ 进行字符串连接:

        section = 'C_type'
        new_section = 'Sec_' + section
        

        【讨论】:

          【解决方案7】:

          要在 python 中连接字符串,请使用“+”号

          参考:http://www.gidnetwork.com/b-40.html

          【讨论】:

            猜你喜欢
            • 2015-07-21
            • 2012-01-15
            • 2014-03-31
            • 1970-01-01
            • 1970-01-01
            • 2023-03-08
            • 2012-01-02
            • 2011-11-04
            相关资源
            最近更新 更多