Python Append

• String append: use "+=" operator or join() Method.

>>> str = "python"
>>> str += " tutorial"
>>> str
"python tutorial"
>>> str2 = "EndMemo"
>>> str3 = " -- ".join((str,str2))
>>> str3
"python tutorial -- EndMemo"
• List append: append() method can append an element to a list:
>>> x = [1,2]
>>> x
[1,2]
>>> x.append(3)
>>> x
[1,2,3]
• Dictionary append: use update() method or just define the key and value:
>>> x = {1:2}
>>> x
{1: 2}
>>> x.update({3:4})
>>> x
{1: 2, 3: 4}
>>> x[5] = 6
{1: 2, 3: 4, 5:6}
• File append: open a file with "a" mode, wrote position will be at the end of the file:
>>> with open("tp.txt","a") as f
>>> f.write(".... new line1"); #append line "... new line1" to tp.txt
>>> f.close()





endmemo.com © 2024  | Terms of Use | Privacy | Home