【问题标题】:Python: Regex and String Length in bytePython:正则表达式和字符串长度(以字节为单位)
【发布时间】:2011-09-26 20:56:21
【问题描述】:

我正在用 python 编写一个程序并且有一些问题(我 100% 是 python 新手):

import re

rawData = '7I+8I-7I-9I-8I-'

print len(rawData)

rawData = re.sub("[0-9]I\+","",rawData)
rawData = re.sub("[0-9]I\-","",rawData)

print rawData
  1. 如何使用| 将 2 个正则表达式合并为一个?这意味着它只需使用一个正则表达式操作即可摆脱9I-9I+
  2. len(rawData)返回rawData的长度是字节吗?

谢谢。

【问题讨论】:

  • 就像"[0-9]I[+-]"一样简单
  • 在 Python 2.x 中 rawData 只是一些字节,但在 Python 3 中它将是 Unicode 文本。

标签: python regex string-length


【解决方案1】:

看看区别:

$ python3
Python 3.1.3 (r313:86834, May 20 2011, 06:10:42) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> len('día')   # Unicode text
3
>>> 

$ python
Python 2.7.1 (r271:86832, May 20 2011, 17:19:04) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> len('día')   # bytes
4
>>> len(u'día')  # Unicode text
3
>>>


Python 3.1.3 (r313:86834, May 20 2011, 06:10:42) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> len(b'día')
  File "<stdin>", line 1
SyntaxError: bytes can only contain ASCII literal characters.
>>> len(b'dia')
3
>>> 

【讨论】:

  • 哇。我从来不知道 :( 我在服务器上使用 python 2.6.5。
  • 那么你如何在 python 3 中以字节为单位获得 len?在 python 2 和 python 3 中是否有一种通用的方法来获取字符串的字节长度?
  • 在 Python 3 中,如果你想要字节,你必须使用 b'bytes'
【解决方案2】:

你为什么不采取不同的方法。用replace方法?

【讨论】:

    【解决方案3】:

    len 指的是应用于 unicode 字符串时的字符数(这是细微的,其他答案会刷新更多)、编码字符串中的字节、列表中的项目(或集合或字典中的键) )...

    rawData = re.sub("[0-9]I(\+|-)","",rawData)
    

    【讨论】:

    • @MRAB 我已经读过了。作为 F.C.把它len('día') 在 Python 3 中是 3 是 3,而在 Python 2.x 中是 4。我主要使用 Python 3。 “编码”也没有指代 unicode(在那里使用了错误的词),我指的是字符串,例如:'\x03'。虽然它的长度可能看起来为 4,但它的 len 仅为 1(因为它在打印时只有一个字符)
    猜你喜欢
    • 1970-01-01
    • 2014-10-22
    • 2013-05-07
    • 1970-01-01
    • 2013-06-04
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多