python代码打错怎么删除_如何从python打印输出中删除字符

1586010002-jmsa.png

I am trying to remove extra characters printed out in my print statement from another print statement.

Here is what my code looks like:

print(addedlist) #addedlist = [9,5,1989,1,2,3,4,5,6,7,8,9]

for x in range(0, len(addedlist)):

print('%d->'%addedlist[x],end="")

print('\n')

the output of this looks like this:

[9, 5, 1989, 1, 2, 3, 4, 5, 6, 7, 8, 9]

9->5->1989->1->2->3->4->5->6->7->8->9->

I am trying to remove the last -> characters. I tried doing :

print(addedlist) #addedlist = [9,5,1989,1,2,3,4,5,6,7,8,9]

for x in range(0, len(addedlist)):

print('%d->'%addedlist[x],end="")

print('\b\b\n')

but it didn't work.

How would i go about accomplishing this ?

EDIT:

Just some clarification, I know i can change my original print statement to print it more correctly to avoid trailing -> ... I am after a solution for how to erase trailing '->' this once the mistake has been made

解决方案

I notice you wants to play with carriage return commands. First you need to learn both \b (moves the active position to the previous position) and \r (moves the active position to the start of line) works for current active line.

I think you are working on command line interpreter; at which you explicitly press enter for next line.

On command line interpreter use ; as follows:

>>> print("abb", end=""); print("\b\bcc")

acc

>>> print("a->", end=""); print("\b\b ")

>>> a

If you are using some script then your code should work, see:

Upload$ cat s.py

print ("abcd->", end="")

print ("\b\b ")

Upload$ python3.2 s.py

abcd # notice -> is removed

But this is not much useful, correct approach is what Aशwini चhaudhary has shown in his answer.

Edit: I found you mistake in your code

print('%d->' % addedlist[x], end="")

print('\b\b\n')

You use '\b' to moves the active position to the previous position, but you don't overwrite "->", you just outputs '\n' that shift cursors to next line, you should rectify your code as below.

print('%d->' % addedlist[x], end="")

print('\b\b \n')

# ^^^ /b then overwrite with spaces

Run at Linux shell as $ python scriptname.py (For command line Python's interpreter you can use something like code I written, it is just to play, use str.join or use sep parameter in print()).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值