【问题标题】:How do I know if a function returns string or bytes?我如何知道函数返回的是字符串还是字节?
【发布时间】:2020-10-31 18:09:34
【问题描述】:

例如os.listdir('.') 返回字符串列表,而os.listdir(b'.') 返回字节对象列表。这只是一个例子,但问题是所有返回字符串/字节的函数。

我没有在官方文档中看到提到返回的类型。是否有一些约定或通用文档?

【问题讨论】:

标签: python python-3.x string byte


【解决方案1】:

来自docs

path 可能是一个类似路径的对象。如果 path 是 bytes 类型(直接或间接通过 PathLike 接口),则返回的文件名也将是 bytes 类型;在所有其他情况下,它们将是 str 类型。

不确定您所指的所有其他功能

【讨论】:

【解决方案2】:

要检查变量的类型,您可以使用内置的 python 函数type()
例如:

# a function that return the parameter that you give
f = lambda x: x 
# here is how type() works
print(type(f('hey this is a string!'))) # returns <class 'str'>
print(type(f(b'hey these are bytes!'))) # returns <class 'bytes'>
print(type(f(['this','is','a','list']))) # returns <class 'list'>
print(type(f(3.1415))) # returns <class 'int'>

所以要检查变量是否包含字符串或字节...

def check(x):
  if type(x) is str:
    return 'this is a string!'
  elif type(x) is bytes:
    return 'i like bytes!'
  else:
    return 'ooops... unknown type :('

myStr = 'string!'
myBytes = b'bytes!'
print(check(myStr))
print(check(myBytes))

您应该做的只是获取路径并检查其类型;)
但是,如果您输入的参数是字节,os.listdir() 函数应该返回字节,否则返回字符串。
要了解有关type() 的更多信息,请阅读this!
希望这有帮助:)

【讨论】:

  • 感谢您的详细回答。我知道类型,但具体的文档是我一直在寻找的,它提供了更广泛的字符串/字节返回值的信息。
猜你喜欢
  • 2019-09-02
  • 2021-02-04
  • 2013-09-03
  • 1970-01-01
  • 2017-05-23
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多