簡體   English   中英

我怎么知道函數返回的是字符串還是字節?

[英]How do I know if a function returns string or bytes?

例如os.listdir('.')返回字符串列表,而os.listdir(b'.')返回字節對象列表。 這只是一個例子,但問題是所有返回字符串/字節的函數。

我還沒有在官方文檔中看到提到返回類型。 是否有一些約定或通用文檔?

文檔

path 可能是一個類似路徑的對象。 如果路徑是字節類型(直接或間接通過 PathLike 接口),則返回的文件名也將是字節類型; 在所有其他情況下,它們將是 str 類型。

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

要檢查變量的類型,您可以使用內置的 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()更多信息,請閱讀此內容!
希望這有幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM