Print and join statement in python

2020-05-01 04:47发布

I am newbie to python. I have a sequence and I am able to print it using join method and able to print the length of the sequence separately. I am not able to print both together. What I so far is:

>>> str = "-";
>>> seq = ("a", "b", "c"); 
>>> print str.join( seq );
   a-b-c
>>> print len(seq)
   3

I want to print both the str.join(seq) and len(seq) together in one line, with some lines like this (My desired output):

The join output is: a-b-c   The length is: 3 

All of this in one line. Is it possible in python?

3条回答
手持菜刀,她持情操
2楼-- · 2020-05-01 05:01

First of all, don't use str as a variable name. This is a built-in; using it as a variable name means you can't access it (e.g. to convert other items to strings).

Secondly, I would recommend string formatting here:

print "The join output is: {0}. The length is: {1}.".format("-".join(seq), 
                                                            len(seq))
查看更多
Juvenile、少年°
3楼-- · 2020-05-01 05:06
seq = ('a', 'b', 'c')
joined = '-'.join(seq)
print('The join output is:', joined, 'The length is:', len(seq))

or

print('The join output is: ' + joined + ' The length is: ' + str(len(seq)))
查看更多
狗以群分
4楼-- · 2020-05-01 05:23

Yes I second @jonrsharpe str is buit-in and use should not use that name.

print " The join o/p is %s and The length is %s"%(s.join(seq),len(s.join(seq)))

Here your length is not 3 it will be 5. Since you have added 2 '-'. If you want to count excluding '-' then use line below.

print " The join o/p is %s and The length is %s"%(s.join(seq),len(s.join(seq).replace('-','')))
查看更多
登录 后发表回答