16, Using strings in lists in functions


#1

Link

https://www.codecademy.com/courses/python-beginner-nzzVa/3/5?curriculum_id=4f89dab3d788890003000096#

Code

def join_strings(words):
result = ""
for i in range(len(words)):
result = result.join(words)
return result

Output

MichaelMichaelLiebermanLieberman
None

I'm not sure how my code produced the output. Any insights would be appreciated.

Melissa


#2

@mnikolic1,

print("\n=== joining a list to a string ===\n")
def join_strings(words):
 result = ""
 for i in range(len(words)):
     print("{0}<>{1}<>{2}".format(i,words,result))
     result = result.join(words)
 return result
 
print join_strings(["Michael","Lieberman"])

print("\n=== concatenating a string ===\n")
def join_strings(words):
 result = ""
 for i in range(len(words)):
     print("{0}<>{1}<>{2}".format(i,words[i],result))
     result = result + words[i]
     # you could also use:: result += words[i]
 return result
 
print join_strings(["Michael","Lieberman"])

giving the output

=== joining a list to a string ===

0<>['Michael', 'Lieberman']<>
1<>['Michael', 'Lieberman']<>MichaelLieberman
MichaelMichaelLiebermanLieberman

=== concatenating a string ===

0<>Michael<>
1<>Lieberman<>Michael
MichaelLieberman

Reference::
google search
== discussions / opinions ==
python join site:stackoverflow.com
for instance
http://stackoverflow.com/questions/1876191/explain-python-join
http://stackoverflow.com/questions/5850986/joining-elements-of-a-list-python


#3

I used the following code which worked for me.

n = ["Michael", "Lieberman"]
def join_strings(words):
result = ""
for i in range(len(words)):
result = result + words[i]
return result
print join_strings(n)

output:
MichaelLieberman
None


#4

Thank you both for your insights.

For my previous code the join() function joined the list [] to the string "" and that's why it gave the output?

Can someone offer a scenario for when to use the join() function?

Thanks again.

Melissa


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.