Joining Strings


print "Words:" + word1 + word2 + word3 + word4 print "List: " + ' '.join(wordList)

Strings can be joined together using a simple add operation, formatting the strings together or using the join() method. Using either the + or += operation is the simplest method to implement and start off with. The two strings are simply appended to each other.

Formatting strings together is accomplished by defining a new string with string format codes, %s, and then adding additional strings as parameters to fill in each string format code. This can be extremely useful, especially when the strings need to be joined in a complex format.

The fastest way to join a list of strings is to use the join(wordList) method to join all the strings in a list. Each string, starting with the first, is added to the existing string in order. The join method can be a little tricky at first because it essentially performs a string+=list[x] operation on each iteration through the list of strings. This results in the string being appended as a prefix to each item in the list. This actually becomes extremely useful if you want to add spaces between the words in the list because you simply define a string as a single space and then implement the join method from that string:

word1 = "A" word2 = "few" word3 = "good" word4 = "words" wordList = ["A", "few", "more", "good", "words"] #simple Join print "Words:" + word1 + word2 + word3 + word4 print "List: " + ' '.join(wordList) #Formatted String sentence = ("First: %s %s %s %s." % (word1,word2,word3,word4)) print sentence #Joining a list of words sentence = "Second:" for word in wordList:     sentence += " " + word sentence += "." print sentence


join_str.py

Words:Afewgoodwords List: A few more good words First: A few good words. Second: A few more good words.


Output from join_str.py code




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net