• 合并字符串


     1 # -*- coding: utf-8 -*-
     2 """
     3  合并字符串
     4  
     5  涉及的函数
     6  join():性能优于+操作
     7  formatString % (pieces):对于少量字符串(尤其是变量中的
     8  字符串),需要拼接,或者还需要加入额外的信息,该方法较好
     9  %s暗中帮我们做了很多工作,如调用str方法,还能指定浮点数的
    10  输出有效位数
    11  +:不要用它来创建大的字符串,psyco编译器可大幅降低+=的性能损失
    12  operator.add
    13  
    14  python字符串无法改变,对字符串的操作将产生一个新的对象
    15  拼接N个字符串将舍弃N-1个中间的结果
    16  但不创建结果,可能提高性能,但是往往不能一步到位得到结果
    17  
    18  
    19 """
    20 # 字符串list的拼接
    21 strList = ['abc','edf','ghi']
    22 
    23 joinStrList = ''.join(strList)
    24 print joinStrList
    25 # Output:abcedfghi
    26 joinStrListWithDot = ','.join(strList)
    27 print joinStrListWithDot
    28 # Output:abc,edf,ghi
    29 joinStrListWithDotSpace = ', '.join(strList)
    30 print joinStrListWithDotSpace
    31 # Output:abc, edf, ghi
    32 
    33 # 变量中字符串的拼接
    34 smallStr1 = 'Good'
    35 smallStr2 = ' Good'
    36 smallStr3 = ' Study'
    37 smallStr4 = 'Day Day Up!'
    38 varStr = '%s%s%s,%s' % (smallStr1, smallStr2, smallStr3, smallStr4)
    39 print varStr
    40 
    41 # + 也可以拼接
    42 plusSignStr = smallStr1 + smallStr2 + smallStr3
    43 print plusSignStr
    44 # Output:Good Good Study
    45 
    46 strList = ['abc','edf','ghi','jkl']
    47 plusSignStrFor = ''
    48 
    49 for piece in strList:
    50     plusSignStrFor += piece
    51 print plusSignStrFor
    52 # Output: abcedfghijkl
    53 
    54 # 更加紧凑和漂亮的方式
    55 import operator
    56 opStr = reduce(operator.add,strList,'')
    57 print opStr
    58 # Output: abcedfghijkl
  • 相关阅读:
    Objective-C 在Categroy中创建属性(Property)
    iOS截屏
    iOS简易图片选择器 (图片可多选,仿微信)
    iOS 3D touch 使用技巧
    soap request by afnetworking2.X/3.X
    类似网易新闻 title栏 滚动时 文字放大&变色
    iOS 用collectionview 做的无限图片滚动 广告banner适用
    iOS WebP转换工具
    微博app中常用正则表达式
    python中property(lambda self: object())简单解释
  • 原文地址:https://www.cnblogs.com/tmmuyb/p/3794718.html
Copyright © 2020-2023  润新知