30秒学会 Python 片段 · 2020年2月19日

30秒学会 Python 片段 – byte_size

Returns the length of a string in bytes.

Use s.encode('utf-8') to encode the given string and return its length.

代码实现

def byte_size(s):
  return len(s.encode('utf-8'))

使用样例

byte_size('😀') # 4
byte_size('Hello World') # 11