# Joining strings quite simple -- first thing many of us learn to do: name = 'World' msg = 'Hello, ' + name + '!' print(msg)
# + only works for string objects -- it won't automatically convert non-strings for you. count = 42 # Error ("TypeError: must be str, not int") # msg = 'The count is ' + 42 # Can convert manually... msg = 'The count is ' + str(42) # Another way to do this is to format the string instead of concatenating msg2 = 'The count is %s' % 42 msg2
'The count is 42'
# Splitting strings also quite easy, as shown by these comma-separated stooges stooge_names = 'Moe,Larry,Curly' stooges = stooge_names.split(',') print(type(stooges)) print(stooges) # Another easy example sentence = 'find the words in this sentence' print(sentence.split(' '))
<class 'list'> ['Moe', 'Larry', 'Curly'] ['find', 'the', 'words', 'in', 'this', 'sentence']
# Default for split character is any whitespace # This sometimes is used as a quick way to get a list of strings: suits = 'hearts clubs spades diamonds'.split() suits
['hearts', 'clubs', 'spades', 'diamonds']