Python: String concatenation

Operating environment ・ Windows 10 ・ Python2.7

How to handle character strings

I used to concatenate strings with +, but I heard that it would affect speed and use a lot of memory, so I thought there was a good way to do it, so I searched for it.

Store in list and then concatenate to string

Test1.py


# -*- conding: utf-8 -*-

class Test():

    def __init__(self):
        #Create a list to store strings
        self.testList = []

    def main(self):
        self.testList.append("abc")
        self.testList.append("def")

        #Concatenate elements that are not listed with a single-byte space
        self.testStr = " ".join(self.testList)

        print self.testStr

if __name__ == '__main__':
    test = Test()
    test.main()

Test1.py output


abc def

It seems that this method can be fast! In java, there is StringBuilder, but it looks similar.

Postscript (2016/10/14)

I tried the method of comment from @ _ha1f!

Test2.py


# -*- conding: utf-8 -*-

if __name__ == '__main__':
    print "{} {}".format("abc", "def")

    print u"{} {}".format(u"Ah", u"Eoka")

Test2.py output


abc def
Ah Eoka

I also changed the variable name to something other than List or str.

Reference site HDE Lab Super Word Theory

Recommended Posts

Python: String concatenation
Python string
Python string format
python string slice
Python2 string type
Python string format
Python # string type
Python string inversion
String manipulation in python
[Python] Multi-line string assignment
Python string manipulation master
[Python2] Date string-> UnixTime-> Date string
Random string generation (Python)
Python3> documentation string / docstring
Python string processing illustration
[python] Convert date to string
Python indentation and string format
How to write string concatenation in multiple lines in Python
Python
String object methods in Python
[Python] Use a string sequence
Various Python built-in string operations
[Python 2/3] Parse the format string
About Python string comparison operators
String date manipulation in Python
Python f character (formatted string)
String format with Python% operator
String replacement with Python regular expression
6 ways to string objects in Python
python string processing map and lambda
Create a random string in Python
kafka python
Conversion of string <-> date (date, datetime) in Python
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python comprehension
Python technique
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
python tips
String format
python function ①
Python basics
Python memo
ufo-> python (3)
Python comprehension
install python
Python Singleton
(Java, JavaScript, Python) Comparison of string processing
Python basics ④
Python Memorandum 2
python memo
Python UTC ⇔ JST, character string (UTC) ⇒ JST conversion memo
Python Jinja2
Python increment
atCoder 173 Python