简体   繁体   中英

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\'

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM