python - 什么是字节数组?为什么使用它?

标签 python arrays

我正在 CoderByte 练习中查看其他人的代码。我刚刚复习了第一个复习字符串的练习。

这是代码:

def FirstReverse(s): 
  ar = bytearray(s)
  ar.reverse()
  return str(ar) 
print FirstReverse("Argument goes here")

我在第一行之后打印了 ar 并刚刚取回了字符串,所以我不清楚 bytearray 有什么帮助。阅读这里的文档后我仍然不明白:https://docs.python.org/2/library/functions.html#bytearray

那么什么是字节数组?在这个例子中使用它有意义吗?

最佳答案

作为doc说,

Return a new array of bytes. ... is a mutable sequence of integers in the range 0 <= x < 256

例如,

 >>> s = 'hello world'
 >>> print bytearray(s) 
 hello world
 >>> bytearray(s)[0] 
 104

104h 的 ASCII 部分。

bytearray有方法reverse,但string没有。为了反转字符串,这段代码首先获取它的bytes数组,然后保留,最后通过str得到反转后的字符串。

此外,您还可以使用[::-1]来反转字符串。

>>> 'Argument goes here'[::-1]
'ereh seog tnemugrA'

关于python - 什么是字节数组?为什么使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32491484/

相关文章:

arrays - Swift 中多维数组的语法是什么?

arrays - 为什么我不能创建一个泛型类型的数组?

php - 如何通过前缀分隔php数组项

arrays - iOS swift : How to find unique members of arrays of different types based on specific attributes

python - 函数类型 : y =10^((a-x)/10*b) 的曲线拟合

python - Django Rest Framework 发送验证邮件

python - 确保两条消息来自同一 MPI 任务

python - 从文件中获取字数,忽略 python 中的注释行

python - 具有可自定义线宽的 Python 中的隐式绘图?

arrays - 快速显示重复循环中的数组输出