Python Forum
name.split() + (And) + print question
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
name.split() + (And) + print question
#11
for display:
>>> out = ["Bob", "Alice"]
>>> print(f"Hello {' and '.join(out) if out else 'stranger'}")
Hello Bob and Alice
>>> out.pop()
'Alice'
>>> print(f"Hello {' and '.join(out) if out else 'stranger'}")
Hello Bob
>>> out = []
>>> print(f"Hello {' and '.join(out) if out else 'stranger'}")
Hello stranger
>>> 
I speak Python but I don't speak English (I just read it a little). If I express myself badly, please blame the translator^^.
Reply
#12
(Mar-26-2022, 02:53 PM)deanhystad Wrote: Your latest question is how do you print "Hello Bob!" or "Hello Bob & Alice!" depending on if you have 1 name or 2 names (or "Hello Stranger!" if there are no names). Or am I way off base?

Assuming I am correct, are you allowed to use str.join()? That might be helpful.

You do not need to cover all possible combinations in your logic. You only have three possibilities:
If no names print "Hello Stranger!"
If one name print "Hello name!" replacing name with the actual name.
if more than one name print "Hello name0 and name1!" replacing name0 and name1 with actual names. This last case can be extended to any number of names > 1.

Collecting the names can be easily done if you know all the possible names.
names = []
for word in input("Hello! ").split():
    if word in ("Bob", "Alice"):
        names.append(word)

Thats interesting! I am trying to wrap my head around .join() , i understand what it does but i cant figure out how to apply it to your idea of the code!
how would i add ".append" the names into the variable "word" , so it basically prints out the demanding names?

Basically I am on day 5 learning python as my first language, i am going to become a front end webbapp developer in JavaScript/Typescript with react as my first job. But i wanted to use python as a back end for my long journey as a developer and i know python will be very useful in my career.. I am sitting like 6-10 hours a day trying to learn now. So i am just messing around and figure things out as they come. So i am allowed to use anything.

Learning alot from this thank you guys!
Reply
#13
names = ['Bob', 'Carol', 'Ted', 'Alice']
print(f"Hello {' & '.join(names)}!")

names=["Alice"]
print(f"Hello {' & '.join(names)}!"))
Output:
Hello Bob & Carol & Ted & Alice! Hello Alice!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Question on "define function"; difference between return and print extricate 10 4,721 Jun-09-2020, 08:56 PM
Last Post: jefsummers
  Self Paced Web course - split ip and print each piece in binary and hex sumncguy 2 2,309 Dec-04-2019, 06:03 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020