美文网首页工作生活
字符串拼接的多种方式

字符串拼接的多种方式

作者: 0981b16f19c7 | 来源:发表于2019-07-01 10:26 被阅读0次

方法一:+

s1="hello"

s2="world"

s3=s1+s2

print(s3)

方法二:join

str.join(sequence)

sequence -- 要连接的元素序列。

示例:

s1="-"

s2=['hello','world']

s3=s1.join(s2)

print(s3)

方法三:用%符号拼接

s1="hello"

s2="world"

s3="%s-%s"%(s1,s2)

print(s3)

方法四:format连接

s1="hello"

s2="world"

s3="{0}-{1}".format(s1,s2)

print(s3)

方法五:string模块的Template

from string import Template

fruit1 ="apple"

fruit2 ="banana"

fruit3 ="pear"

str = Template('There are ${fruit1}, ${fruit2}, ${fruit3} on the table')

print(str.safe_substitute(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3))

print(str.safe_substitute(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3) )

效率比较:+号和join

结论:join的性能远高于+

原因:1)使用 + 进行字符串连接的操作效率低下,是因为python中字符串是不可变的类型,使用 + 连接两个字符串时会生成一个新的字符串,生成新的字符串就需要重新申请内存,当连续相加的字符串很多时(a+b+c+d+e+f+...) ,效率低下就是必然的了。2)join使用比较麻烦,但对多个字符进行连接时效率高,只会有一次内存的申请。而且如果是对list的字符进行连接的时候,这种方法必须是首选

示例佐证:

import time

def decorator(func):

    def wrapper(*args, **kwargs):

        start_time = time.time()

        func()

        end_time = time.time()

        print(end_time - start_time)

    return wrapper

@decorator

def method_1():

    s = ""

    for i in range(1000000):

        s += str(i)

@decorator

def method_2():

    l = [str(i) for i in range(1000000)]

    s = "".join(l)

method_1()

method_2()

结果:

1.940999984741211

0.2709999084472656

相关文章

  • 字符串拼接的多种方式

    方法一:+ s1="hello" s2="world" s3=s1+s2 print(s3) 方法二:join s...

  • 【Go 字符串】如何连接字符串

    Go有多种字符串拼接方式,不同方式的效率不同: 使用加号+ bytes.Buffer strings.Builde...

  • iOS UIImage图片拼接性能对比

    前言 这篇主要来介绍图片拼接,封装多种拼接方式供使用 多种图片水平和竖直拼接 更多好玩的拼接方式,大致包含平铺、两...

  • Golang 字符串拼接

    字符串拼接应该在编程过程中比较常用的操作了,在Go语言中对字符串的拼接有多种处理方式,以下通过实例来一一讲解 +号...

  • 谈谈PHP中的单引号和双引号

    我们在做字符串拼接的时候,有多种方式,最常用的莫过于使用单引号和双引号拼接了,当让sprintf()也用的比较多,...

  • go语言string之Buffer与Builder

    操作字符串离不开字符串的拼接,但是Go中string是只读类型,大量字符串的拼接会造成性能问题。 字符串拼接的方式...

  • mybatis--获取参数的方法

    获取参数的两种方式:#{}与${} {}与${}区别: {}使用字符串拼接的方式拼接sql,若为字符串类型或日期类...

  • C# string 拼接操作性能测试

    一、C# 拼接字符串的几种方式和性能 对于少量固定的字符串拼接,如string s= "a" + "b" + "c...

  • 我眼中一个好的Pythoneer应该具备的品质(二)

    知道python中的几种字符串拼接方式与效率对比。 使用+拼接 使用%拼接 使用join 使用f''f-strin...

  • Sql中字符串拼接

    SQL语句中字符串拼接 注意:oracle中虽然有concat函数,但是只能拼接2个字符串,所以建议用||的方式;...

网友评论

    本文标题:字符串拼接的多种方式

    本文链接:https://www.haomeiwen.com/subject/jxpwcctx.html