The difference between Python's "+" and append when adding strings

Source: Internet
Author: User
Tags python list

For an empty Python list, there are a number of things to add later, two of which are adding content directly with "+" and the other is Listname.append (x) to add content

Where, if the string is processed

When using "+", the string is split into list elements, added to the list, and append is used to package the string into an element and add it to the list.

For example, if you use append:

  

all = []
Print "\nenter lines ('. ' by itself to quit). \ n"

While True:
Entry = Raw_input (">")
If entry = = '. ':
All.append (".")
Break

Else

Print all
Print "done!"

Assuming the input to the content is Hello, world, then the result is:

Enter lines ('. ' by itself to quit).

>hello
>world
.
[' Hello ', ' world ', '. ']
done!

If you are using "+":

all = []
Print "\nenter lines ('. ' by itself to quit). \ n"

While True:
Entry = Raw_input (">")
If entry = = '. ':
All.append (".")
Break

Else
all+= (Entry)
Print all
Print "done!"

Then the output is:

Enter lines ('. ' by itself to quit).

>hello
>world
.
[' H ', ' e ', ' l ', ' l ', ' o ', ' w ', ' O ', ' r ', ' L ', ' d ', '. ']
done!

The difference between Python's "+" and append when adding strings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.