Abhinav Abhinav - 2 years ago 85
Python Question

Not getting desired output by adding character before and after each item in list

I am trying to take multiple input from a user and store it in a variable. After storing I want to add character starting and ending of each word, but I am failing to get desired output in python 3.X

My code is as follows:-

string_value=[str(i) for i in raw_input("Enter space separated inputs: ").split()]
aces = ["\'" + string_value + "\'" for string_value in string_value]
print (aces)


Output:-

Enter space separated inputs: John Sunil Kathylene Bob

["' John ' ", " ' Sunil ' ", " ' Kathylene ' ", " ' Bob' "]


Desired Output :-

\'John\',\'Sunil\',\' Kathylene\',\' Bob\'

Answer Source

Some advise:

  • Read PEP8.
  • Type-casting of str to str is redundant.

Code:

words = input("Enter space separated inputs: ").split()
prefix_and_suffix = "\\'"
formatted_words = ','.join('{0}{1}{0}'.format(
    prefix_and_suffix, word) for word in words)
print (formatted_words)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download