0

Let's say I have these values in an excel sheet:

`"Hello!"

"Testing!"

"My name is " + random.choice(random_names) + "."

"Goodbye!'`

I already have the random_names list earlier in my program:

random_names = ["Harry", "Sam", "Albert"]

How can I transfer these values from an excel sheet into a python list? When I try doing it using openpyxl:

(for phrase_cell in phrase_sheet['A']: 
    random_phrases_list.append(phrase_cell.value)

I get a list that looks like this when printed:

['"Hello!"', '"Testing!"', '"My name is " + random.choice(random_names) + "."', '"Goodbye!"']

This doesn't work, because when I print the 3rd (i=2) value of the list, this is the output:

"My name is " + random.choice(random_names) + "."

If I remove the quotes from my excel sheet, I get a list that looks like this:

['Hello!', 'Testing!', 'My name is + random.choice(random_names) + .', 'Goodbye!']

And when I print the 3rd value of the list, this is the output:

My name is + random.choice(random_names) + .

Any way I can remove the single quotes that surround each value of the list so that my list would look like this:

["Hello!", "Testing!", "My name is " + random.choice(random_names) + ".", "Goodbye!"]

And if I printed the 3rd value of this list it would be this (for example):

My name is Albert.

Tekko
  • 3
  • 2
  • https://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python – BigBen Apr 27 '23 at 17:53
  • [This comment is very relevant however](https://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python#comment514609_701802). – BigBen Apr 27 '23 at 17:54

1 Answers1

0

You will never get that desired output. The reason being is that the values from excel are string values and random.choice() is a python function. Your third value '"My name is " + random.choice(random_names) + "."' is a string value that has nothing to do with python. Your issues has nothing to do with the quotations.

One possible solution would be to append your function to the random_phrases_list. Here is what I believe what you were trying to do:

import random
random_names = ['Harry', 'Sam', 'Albert']

random_phrases_list = ['Hello!', 'Testing!', 'Goodbye!']

def my_name_is_function():
    name = random.choice(random_names)
    return 'My name is ' + name + '.'

random_phrases_list.append(my_name_is_function)

print(random_phrases_list[3]())
My name is Harry.
jmetzg11
  • 56
  • 4