1

I have a list in python as :

values = ['Maths\n', 'English\n', 'Hindi\n', 'Science\n', 'Physical_Edu\n', 'Accounts\n', '\n']
print("".join(values))

I want output should be as :-

Subjects: Maths English Hindi Science Physical_Edu Accounts

I am new to Python, I used join() method but unable to get expected output.

Jan
  • 42,290
  • 8
  • 54
  • 79
Rahul Arora
  • 55
  • 1
  • 7
  • Thank you for your question, but please update it to show the code you have written so far. – quamrana Oct 25 '17 at 09:56
  • I used below code to print list elements print("".join(values)) Output is :- Maths English Hindi Science Physical_Edu Accounts Plus Two Line Space But I want ourput in a single line only separated by space. – Rahul Arora Oct 25 '17 at 10:00
  • 1
    What's your code and actual output? Since there's "\n" in your list, there should be multilines in your output if you do not trim or replace "\n". – osfans Oct 25 '17 at 10:01
  • Ok, I'll update the question myself with this new information. – quamrana Oct 25 '17 at 10:01

4 Answers4

6

You could map the str.stripfunction to every element in the list and join them afterwards.

values = ['Maths\n', 'English\n', 'Hindi\n', 'Science\n', 'Physical_Edu\n', 'Accounts\n', '\n']

print("Subjects:", " ".join(map(str.strip, values)))
miindlek
  • 3,523
  • 14
  • 25
  • You need to add space between items, your code will print them without it – Chen A. Oct 25 '17 at 10:01
  • 1
    You could even use `.rstrip()` as the newline characters only appear on the right side of the string (+1 though). – Jan Oct 25 '17 at 10:20
  • @Jan right! To be more explicit, you could even use `.rstrip("\n")`. But I guess `str.strip` is perfectly fine in this case. – miindlek Oct 25 '17 at 10:31
1

Using a regular expression approach:

import re

lst = ['Maths\n', 'English\n', 'Hindi\n', 'Science\n', 'Physical_Edu\n', 'Accounts\n', '\n']

rx = re.compile(r'.*')
print("Subjects: {}".format(" ".join(match.group(0) for item in lst for match in [rx.match(item)])))
# Subjects: Maths English Hindi Science Physical_Edu Accounts 

But better use strip() (or even better: rstrip()) as provided in other answers like:

string = "Subjects: {}".format(" ".join(map(str.rstrip, lst)))
print(string)
Jan
  • 42,290
  • 8
  • 54
  • 79
0

What you can do is use this example to strip the newlines and join them using:

joined_string = " ".join(stripped_array)
ronald kok
  • 38
  • 7
0

strip() each element of the string and then join() with a space in between them.

a = ['Maths\n', 'English\n', 'Hindi\n', 'Science\n', 'Physical_Edu\n', 'Accounts\n', '\n']
print("Subjects: " +" ".join(map(lambda x:x.strip(), a)))

Output:

Subjects: Maths English Hindi Science Physical_Edu Accounts 

As pointed out by @miindlek, you can also achieve the same thing, by using map(str.strip, a) in place of map(lambda x:x.strip(), a))

Miraj50
  • 4,257
  • 1
  • 21
  • 34