0

I want to make a text using python generator

I'm a beginner and have started learning python recently , I have searched the web but didn't find anything useful

def make_text(n):
    b = ["hello"]
    yield n+b
n = ['how are you', 'what is your name']
for x in range(2):
    title = driver.find_element_by_xpath('//*[@id="title"]')
    title.send_keys(make_text(n))

I want to get :

hello how are you 
hello what's your name? 

but i get this error :

object of type 'generator' has no len() 

thanks in advance

7
  • 2
    why don't you use return n+b instead of yield n+b? Commented Apr 3, 2019 at 12:42
  • 2
    A generator is meant to be used along with iteration over the generator. I don't se that in the code. Your code will not throw that error if you iterate over make_text() Commented Apr 3, 2019 at 12:43
  • 1
    title.send_keys checks the len of the argument passed ? If that is the case, then you can't pass the generator to the title.send_keys :). Anyway, why are you using generators for this ? Commented Apr 3, 2019 at 12:47
  • 1
    @hansolo I want to have "hello how are you " first time that the loop runs and hello what's your name second time Commented Apr 3, 2019 at 13:06
  • 1
    @reportgunner I want it to be a generator exactly, I don't think it would be a generator without yield Commented Apr 3, 2019 at 13:08

2 Answers 2

2

Here's a basic sample of what you can do. You need to iterate the yielded object,

def make_text(word):
    greetings = ['how are you', 'what is your name']
    for greet in greetings:
        yield "{} {}".format(word, greet)

def say():
    texts = ['hello',]
    for text in texts:
        x = make_text(text)
        for n in x:
            print(n)
            title = driver.find_element_by_xpath('//*[@id="title"]')
            title.send_keys(n)


say()

Output,

hello how are you
hello what is your name
Sign up to request clarification or add additional context in comments.

Comments

0

A more beginner-friendly version of your code would be:

def make_text(n):
    b = ["hello"]
    return n + b

words = ['how are you', 'what is your name']

for word in words:
    text = make_text(word)
    print(text)

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.