如何在 Python 中获取字符串的大小? [英] How to get the size of a string in Python?

查看:141
本文介绍了如何在 Python 中获取字符串的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我得到一个字符串:

str = "请回答我的问题"

我想将其写入文件.

但是在将字符串写入文件之前我需要知道字符串的大小.我可以使用什么函数来计算字符串的大小?

解决方案

如果你说的是字符串的长度,你可以使用 len():

<预><代码>>>>s = '请回答我的问题'>>>len(s) # s 中的字符数25

如果需要以字节为单位的字符串大小,则需要 sys.getsizeof():

<预><代码>>>>导入系统>>>sys.getsizeof(s)58

另外,不要调用你的字符串变量str.它隐藏了内置的 str() 功能.

For example, I get a string:

str = "please answer my question"

I want to write it to a file.

But I need to know the size of the string before writing the string to the file. What function can I use to calculate the size of the string?

解决方案

If you are talking about the length of the string, you can use len():

>>> s = 'please answer my question'
>>> len(s)  # number of characters in s
25

If you need the size of the string in bytes, you need sys.getsizeof():

>>> import sys
>>> sys.getsizeof(s)
58

Also, don't call your string variable str. It shadows the built-in str() function.

这篇关于如何在 Python 中获取字符串的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆