如何摆脱print语句中的额外+符号,Python

时间:2016-10-03 10:48:38

标签: python python-3.x printing

print('2**', n, ' + ', sep='', end='')

上面的print语句是循环的,所以输出最终是

2 ** 10 + 2 ** 7 + 2 ** 6 + 2 ** 4 + 2 ** 1 +

我需要摆脱声明中的最后一个加号,但不知道如何去做。

6 个答案:

答案 0 :(得分:2)

如果您将指数分开,可以使用str.join()

>>> exponents = (10, 7, 6, 4, 1)
>>> print(' + '.join('2**{}'.format(n) for n in exponents))
2**10 + 2**7 + 2**6 + 2**4 + 2**1

这将适用于Python 2& 3.您还可以将print()函数与sep参数一起使用:

>>> print(*('2**{}'.format(n) for n in exponents), sep=' + ')
2**10 + 2**7 + 2**6 + 2**4 + 2**1

答案 1 :(得分:1)

非常普通' '问题',通常使用' .join方法解决。我假设你有一个整数列表,所以你需要做的就是:

powers = [10, 7, 6, 4]
print(' + '.join(['2 ** {n}'.format(n= n) for n in powers]))

答案 2 :(得分:0)

您可以将要打印的字符串存储在循环中的变量中,然后在循环结束后,使用to_print[:len(to_print)-1]切片来删除额外的加号 然后打印to_print。 这里to_print是你需要存储在循环中的文本而不是打印它,然后在切片之后打印它,如上所示。

答案 3 :(得分:0)

检查您是否在最后一个元素并使用不同的print语句(没有最终'+'),或者首先在列表中构建输出并在打印前加入列表。

output = []
some_loop:
    output.append('2**%i' % n)

print(' + '.join(output))

答案 4 :(得分:0)

您可以执行以下操作,并使其适应您的循环长度

n = 1
for i in range(0,10):
    if i < 9:
        print('2**', n, ' + ', sep='', end = '')
    else:
        print('2**', n, sep='', end = '')

答案 5 :(得分:0)

在这种情况下,

join()有很多帮助:

$('.tooltiptext .emoticon').click(function() {
      $in = $(this);
      console.log($in);
      setTimeout(function() {
          var dataText = $("#text").val();
          $('#text').append(dataText + $.emoticons.replace($in.html()));
          var dataCode = $in.context.innerText;
          console.log(dataCode);
          var dataTextArea = $("textarea").val();
          console.log(dataTextArea + dataCode);
          //$('#textarea').html('');
          $('#textarea').empty();// it not working
          console.log($('#textarea').val());
          $('#textarea').append(dataTextArea + dataCode + ' ');

      }, 100);

  });

  $('textarea').on('keypress', function(e) {

      if (e.which == 32 || e.which == 8) {
          $in = $(this);
          setTimeout(function() {
              $("#text").html($.emoticons.replace($in.val()));
          }, 100);
      }

  });