我正在 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
和 104
是 h
的 ASCII 部分。
类bytearray
有方法reverse
,但string
没有。为了反转字符串,这段代码首先获取它的bytes数组,然后保留,最后通过str
得到反转后的字符串。
此外,您还可以使用[::-1]
来反转字符串。
>>> 'Argument goes here'[::-1]
'ereh seog tnemugrA'
关于python - 什么是字节数组?为什么使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32491484/