简体   繁体   English

用 Print 替换 python 字符串中的字符 - 奇数 output

[英]Replacing a character in a python string - odd output with Print

I'm trying to make some code that allows me to replace a character in a list where the position is defined by an integer.我正在尝试编写一些代码,允许我替换列表中的字符,其中 position 由 integer 定义。 I have the following code我有以下代码

# -*- coding: utf-8 -*-
a = 47
text = 'xxxxxxxxxx xxxxx ╟───┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼───╢ xx'
new = list(text)
new[a] = "x"
print ''.join(new)

But when I run it, it prints out但是当我运行它时,它会打印出来

xxxxxxxxxx xxxxx ╟───┼────┼x▒▒───┼────┼────┼────┼────┼────┼────┼────┼────┼───╢ xx xxxxxxxxxx xxxxx ╟───┼────┼x▒▒────┼────┼────┼────┼────┼────┼────┼─ ────┼────┼────╢ xx

Instead of代替

xxxxxxxxxx xxxxx ╟───┼────┼x──┼────┼────┼────┼────┼────┼────┼────┼────┼───╢ xx xxxxxxxxxx xxxxx ╟───┼────┼x──┼────┼────┼────┼────┼────┼────┼──── ┼────┼────╢ xx

In other words it includes the "▒▒" in the printed string.换句话说,它在打印的字符串中包含“▒▒”。 It adds extra characters regardless of which character is replaced in the list.无论列表中的哪个字符被替换,它都会添加额外的字符。 What am I doing wrong?我究竟做错了什么?

I'm running it on a raspberry pi connected via SSH using putty.我正在使用腻子通过 SSH 连接的树莓派上运行它。

Since you're using utf-8 encoding for the text (with non-ascii chars), you need to convert it to Unicode string on Python 2 so each char is not split into multiple bytes** before changing to a list.由于您对文本使用 utf-8 编码(使用非 ascii 字符),您需要将其转换为 Unicode 字符串 Python 在更改为每个列表之前将其拆分为多个字节 2 因此

Better yet, you can directly define the the text as unicode string:更好的是,您可以直接将文本定义为 unicode 字符串:

text = u'xxxxxxxxxx xxxxx╟───┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼───╢ xx'

** There are cases where even unicode strings split chars into more than 1 element, but this won't affect you since you're within BMP range. ** 在某些情况下,即使是 unicode 字符串也会将字符拆分为 1 个以上的元素,但这不会影响您,因为您在 BMP 范围内。 If you want to know more, read about UCS-2 vs UCS-4 representations如果您想了解更多信息,请阅读有关UCS-2 与 UCS-4 表示的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM