Python Python Basics (2015) Python Data Types Use .split() and .join()

Josiah Loh
Josiah Loh
186 Points

How do i format string ?

Hello, i am going through python basics lesson where i have to format strings, i do not recall learning how to join strings with , . Can any kind soul teach me how to format strings ?

banana.py
available = "banana split;hot fudge;cherry;malted;black and white"
sundaes = available.split(";")
menu = "Our available flavors are {}.join(sundaes)"
display_menu= menu
dublinruncommutr
dublinruncommutr
5,944 Points

Hi Josiah, In the second line you are splitting the string into a list using the .split() method. Basically you are taking a string and returning a list with this method by "splitting" it via a delimiter (in this case a semi-colon).

Think of the .join() method as performing the opposite functionality: it takes a string and joins it with a list based on a specific delimiter. Both of these are string methods because they are operating on strings - but they return different things: .split returns a list and .join returns a string.

Now let's talk about the .format string method. This takes one or more variables and inserts them into the string where your curly braces are located. For example:

first_name = "Jeff"
example_str = "My name is {}".format(first_name)

would result in:

My name is Jeff.

Now to come full circle, your .split() looks good. Take a look at doing your .join() next and if it's helpful try putting it into it's own variable before using .format() to build your "menu".

2 Answers

Naga pavan kumar kalepu
Naga pavan kumar kalepu
5,909 Points

Below format statement may helpful for you to understand to join strings

menu = "Our available flavors are {}".format(sundaes)

Naga pavan kumar kalepu
Naga pavan kumar kalepu
5,909 Points

Otherwise if you don't want to use format method and you have a list of items to be joined, you can also do as below

menu = ", ".join(sundaes) print menu #'banana split, hot fudge, cherry, malted, black and white' display_menu = "Our available flavors are {}".format(menu) print display_menu. #'Our available flavors are banana split, hot fudge, cherry, malted, black and white'

Steven Parker
Steven Parker
203,443 Points

:warning: Since "sundaes" is a list, supplying it as an argument to "format" would likely not produce the intended output.

Steven Parker
Steven Parker
203,443 Points

One issue with the above code is a function (join) inside quotes, which makes it a string literal instead of an actual function.

To refresh your knowledge of formatting and concatenatiion, you might want to review the Strings and String concatenation videos. And for using the "jon" function, you may want to review the Splitting and Joining video.