How do I append one string to another in Python?

How do I append one string to another in Python?

Asked on October 15, 2018 in Python.
Add Comment


  • 5 Answer(s)

    Do not early improve. If you have no reason to believe there’s a speed bottleneck triggered by string concatenations then simply stick with + and +=:

    s = 'foo'
    s += 'bar'
    s += 'baz'

    This said that, if you’re pointing for somewhat like Java’s StringBuilder, the canonical Python idiom is to add items to a list and then use str.join to concatenate them all at the conclusion:

    l = []
    l.append('foo')
    l.append('bar')
    l.append('baz')
    s = ''.join(l)

     

    Answered on October 15, 2018.
    Add Comment

    That is, for maximum cases you are better off producing the entire string in one go pretty then appending to an present string.
    For instance, don’t do:

     obj1.name + ":" + str(obj1.count)

    In its place: use

     "%s:%d" % (obj1.name, obj1.count)

    That will be more easier to read and more effective.

    Answered on October 15, 2018.
    Add Comment
    str1 = "Hello"
    str2 = "World"
    newstr = " ".join((str1, str2))

    That combines str1 and str2 with a space as separators. You may also do “”.join(str1, str2, …). str.join() takes an iterable, so you would have to put the strings in either a list or a tuple.
    This is all about as effective as it gets for a built-in method.

    Answered on October 15, 2018.
    Add Comment

    Example code ,

    name1 = input("Enter file to be read from: ")
    name2 = input("Enter file to be appended to: ")
    fin = open(name1, "r")
    data2 = fin.read()
    fin.close()
    fout = open(name2, "a")
    fout.write(data2)
    fout.close()
    
    Answered on December 17, 2018.
    Add Comment

    append strings with __add__ function

    str = "Hello"
    str2 = " World"
    st = str.__add__(str2)
    print(st)

    Output

    Hello World
    Answered on January 14, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.