Herpes Qwe
Herpes Qwe

Reputation: 43

How can i use end= " " with in the function?

print(x,end= "") is working but I want to use end= "" in the function so return(x,end= "") didn't work. How can i use it in the function in this code?

def b(a):
   for i in a.split():
      return(i[0],end= "")
b("welcome to the jungle")

wttj is what i want.

Upvotes: 1

Views: 526

Answers (3)

chepner
chepner

Reputation: 530843

end is a parameter specific the print function, not something you can apply to an arbitrary string expression.

If you want the first letter of each word, it's just

def b(a):
    return ''.join(i[0] for i in a.split())

Upvotes: 1

DirtyBit
DirtyBit

Reputation: 16772

Using split() with list comprehension:

sentence = "welcome to the jungle"
splitted = sentence.split()
letters = [word[0] for word in splitted]
print ("".join(letters))

one-liner:

print("".join([word[0] for word in sentence.split()]))

OUTPUT:

wttj

Upvotes: 3

Red
Red

Reputation: 27547

A function can only return a value once, so because you put your return statement inside the for-loop, the function only got the chance to iterate once. Try this:

def b(a):
    c = ''
    for i in a.split():
        c += i[0]
    return c

print(b("welcome to the jungle"))

Upvotes: 1

Related Questions