-4

I have a List , x = ["apple", "banana", "carrot", "cheese", "pear"] and I will write in one line of code that when executed returns "apples bananas carrots cheeses and pears".

Very Thanks for your help!

iratxe
  • 87
  • 9
  • 2
    what did you try so far? Check `str.join()` function: https://docs.python.org/2/library/stdtypes.html#str.join – yedpodtrzitko Feb 04 '17 at 15:35
  • When i write x.join() in my IDLE console a come : AttributeError: 'list' object has no attribute 'join' – iratxe Feb 04 '17 at 15:38
  • 1
    @Wander Nauta , Thanks thas is was I to search! .I have with google to search and I have not to finde this answer.... so , thanks for the link . – iratxe Feb 04 '17 at 15:47
  • @iratxe `x = ["apple", "banana", "carrot", "cheese", "pear"] print("\""+'s '.join(x[:-1])+"s"+" and "+(x[4])+"s"+"\"")` – Yousaf Feb 04 '17 at 15:59
  • @ yedpodtrzitko , I have yesterday five hours and today two hours in google to search , I writing "python removing commas list of string" and all answer what i to find are not what to search .... – iratxe Feb 04 '17 at 16:03
  • @Yousaf , thanks for you example , but as my knowledge about Python are very simple , for me the best answer is this: print ", ".join(x[:-2] + [" and ".join(x[-2:])]) , I Understand well the Python Logic ..... – iratxe Feb 04 '17 at 16:12
  • @Yousaf , sorry for the before answer from me... you answer it is well , because this code : print ", ".join(x[:-2] + [" and ".join(x[-2:])]) not print to ende , the word S , so , you answer it is the best! – iratxe Feb 04 '17 at 17:44

2 Answers2

-1

You need to use join just like octo has said

arr = ["apple", "banana", "carrot", "cheese", "pear"]
my_string = " ".join(arr) 

Well you can also do:

arr = ["apple", "banana", "carrot", "cheese", "pear"]
my_string = ""
for ( n in range(len(arr) ):
  if n > 0:
    my_str += " " + arr[n]
  else:
    my_str += arr[n]

just to make my answer look different than others.

hungryWolf
  • 391
  • 1
  • 3
  • 15
-1

The Best answer is from Yousaf .

x = ["apple", "banana", "carrot", "cheese", "pear"]

print("\""+'s '.join(x[:-1])+"s"+" and "+(x[4])+"s"+"\"")

iratxe
  • 87
  • 9