0

I have a large list of names which is in this format

list1 = ["apple", "orange", "banana", "pine-apple"]

And I want it in this format

list1 = ["'apple'", "'orange'", "'banana'", "'pine-apple'"]

Basically, I want to add punctuation marks to every single word in the list but since the list is too large, I can't do it manually. So is there any python function or way to do this task. Thank You.

1
  • So you want an automated way to edit the python code in your text editor? Which text editor are you using? Commented Nov 14, 2020 at 3:44

3 Answers 3

2

The names in python are already strings enclosed in the quotes like you have shown here. I am supposing you want to wrap the string with specific quote to look this '"apple"' or "'apple'". To do so, you should use the following snippet

q = "'" # this will be wrapped around the string

list1 = ['apple','orange','banana','pine-apple']
list1 = [q+x+q for x in list1]

For reference, the syntax I have used in last line is known as list comprehension

According to latest comment posted by @xdhmoore

If you are using vim/nano (linux/macos) or notepad(windows), then i would rather suggest you to use IDLE python (shipped with python setup)

Sign up to request clarification or add additional context in comments.

Comments

0

Str function is the built in function to convert a value into string. You can run this code;

 For i in range(len(list1)):
       new = str(list1[i])
       list1.remove(list[i])
       list1.append(new)

Comments

0

Using for loop to process each line, two ways to go

text = "list1 = [apple,orange,banana,pine-apple]"
start = text.find('[')+1
stop  = text.find(']')
lst = text[start:stop].split(',')                       # ['apple', 'orange', 'banana', 'pine-apple']
new_lst = [f'"{item}"' for item in lst]                 # ['"apple"', '"orange"', '"banana"', '"pine-apple"']
new_text1 = text[:start]+','.join(new_lst)+text[stop:]  # 'list1 = ["apple","orange","banana","pine-apple"]'
text = "list1 = [apple,orange,banana,pine-apple]"
new_text2 = text.replace('[', '["').replace(']', '"]').replace(',', '","')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.