Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
list and for
#1
I'm new at python programing i read some basic and i have a question. Probably it is easy but i dont know how to do it. (im looking for answer for 2 days)

I have something like this

string="awesome cat";
str=string.split();

for i in str:
    print ('-'.join(i));
And if i print it i have
a-w-e-s-o-m-e
c-a-t

And my question is how i make each i into new string like this "a-w-e-s-o-m-e c-a-t"?

I know its easy but im very basic at programing so im sorry if i hurt anyone with my question.
Reply
#2
Hello!
s="awesome cat"
l=s.split()
out=[]
for s in l:
    out.append('-'.join(list(s)))
print(' '.join(out))
Reply
#3
Just replace space with empty string

print('-'.join("awesome cat".replace(' ', '')))
and the output is
Output:
a-w-e-s-o-m-e-c-a-t

str is Python built-in type/function, and giving names of built-ins to variables is potentially dangerous. Little demonstration
Output:
In [1]: str(1) Out[1]: '1' In [2]: str = 's' In [3]: str(1) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-3-5c73dd08b6cc> in <module>() ----> 1 str(1) TypeError: 'str' object is not callable
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#4
Thanks very much.
Reply


Forum Jump:

User Panel Messages

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