Joining strings ("string concatenation") and splitting them is easy to do

In [4]:
# Joining strings quite simple -- first thing many of us learn to do:

name = 'World'
msg = 'Hello, ' + name + '!'
print(msg)
Hello, World!
In [6]:
# + 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
Out[6]:
'The count is 42'
In [25]:
# 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']
In [2]:
# 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
Out[2]:
['hearts', 'clubs', 'spades', 'diamonds']