Python的中文字符串遍历问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python的中文字符串遍历问题相关的知识,希望对你有一定的参考价值。

Python怎么遍历中文字符串? #encoding=gbk a='测试' for i in a: print i 这样打印的不是中文啊…

参考技术A 首先一个,你这个'a'是什么编码?可能不是你所想的gbk
>>>
a='测试'
>>>
a
这样试试看,如果出来是6个字(word),说明是utf-8,如果是4个字,说明是gbk。
另外,不管是utf-8还是gbk,都不能这样遍历,因为这里它会
一个字
一个字拿出来。
虚拟机
把a当成一个
长度
为len(a)的
字符串
了。
接下来是遍历问题。
linux的shell大都默认是utf-8,所以一个
中文
字符是
三个字
,所以要三个三个地读,你可以试下:
>>>
a[:3]
出来就是个测字
windows的command的默认是cp936,也就是gbk,一个中文字符是
两个字
,所以两个字两个字地读。
还有另一种遍历的方法,把字符串转换成unicode,这样中文
英文
都是一个字,就可以用你的for
i
in
a的方法遍历了。这个的好处是中文英文字符都是一个字,而utf-8和gbk里,
英文字母
只占一个字。

无法阻止python在循环中遍历字符串

【中文标题】无法阻止python在循环中遍历字符串【英文标题】:Can't stop python from iterating through string in loop 【发布时间】:2021-12-14 23:18:15 【问题描述】:
class Hat:
    def __init__(self, **kwargs):
        self.contents = []
        for balltype in kwargs.keys():
            for ballnum in range(kwargs[balltype]):
                self.contents += balltype

hattrial = Hat(red = 1, blue = 2)
print(hattrial.contents)
        

我正在尝试创建一个包含输入参数字典中的键的列表,而不是简单地添加我得到的字符串条目:

['r', 'e', 'd', 'b', 'l', 'u', 'e', 'b', 'l', 'u', 'e']

代替:

['red', 'blue', 'blue']

红色出现一次,蓝色出现两次。我已经尝试了一些不同的解决方案,而不是之后仅操作数组,例如下面的尝试,但我所做的一切都没有改变输出。肯定有一个优雅的解决方案,不需要我将角色重新组合在一起吗?

end = len(balltype)
self.contents += balltype[0:end]
self.contents += balltype

【问题讨论】:

【参考方案1】:

使用append

class Hat:
    def __init__(self, **kwargs):
        self.contents = []
        for balltype in kwargs.keys():
            for ballnum in range(kwargs[balltype]):
                self.contents.append(balltype)

hattrial = Hat(red = 1, blue = 2)
print(hattrial.contents)

注意列表中的+= 运算符

这也有效,尝试理解为什么它在此处正确附加+=

class Hat:
    def __init__(self, **kwargs):
        self.contents = []
        for balltype in kwargs.keys():
            self.contents += kwargs[balltype] * [balltype]

hattrial = Hat(red = 1, blue = 2)
print(hattrial.contents)

基本上,您的代码问题可以归结为以下几点:

a = []
a += "hello"
a
['h', 'e', 'l', 'l', 'o']

【讨论】:

以上是关于Python的中文字符串遍历问题的主要内容,如果未能解决你的问题,请参考以下文章

无法阻止python在循环中遍历字符串

防止 Python For 循环通过 char 遍历单个字符串

如何在python中遍历地图的元素

动态循环遍历Python函数中的函数列表

遍历现有键并更新字典python

字符串的遍历