Python获取字符串长度

Python获取字符串长度教程

Python 中要想获取 字符串 长度可以使用 len() 函数。

Python len()函数详解

定义

我们将要获取的字符串的长度,传进 len() 函数,即可实现获取字符串的长度。

语法

len(string)

参数

参数 描述
string 要获取长度的字符串。

返回值

返回一个 int 类型的字符串的长度。

案例

获取字符串长度

使用 len() 函数,获取字符串的长度

print("嗨客网(www.haicoder.net)") # 使用 len() 函数,获取字符串的长度 str1 = "Hello,HaiCoder" print('len =', len(str1))

程序运行后,控制台输出如下:

09 python获取字符串长度.png

首先,我们定义了一个字符串 变量,赋值为 “Hello,HaiCoder,”,接着我们使用 len() 函数,获取该字符串的长度,并使用 print() 函数,打印该字符串的长度。

获取中文字符串长度

使用 len() 函数,获取中文字符串的长度

print("嗨客网(www.haicoder.net)") # 使用 len() 函数,获取中文字符串的长度 str1 = "Hello,嗨客网(HaiCoder)" print('len =', len(str1))

程序运行后,控制台输出如下:

10 python获取字符串长度.png

首先,我们定义了一个包含中文的字符串变量,赋值为 “Hello,嗨客网(HaiCoder)”,接着我们使用 len() 函数,获取该字符串的长度,并使用 print() 函数,打印该字符串的长度,输出了 19,即我们发现一个中文算了一个长度。

Python获取字符串长度总结

在 Python 要想获取字符串长度可以使用 len() 函数。Python len() 函数语法:

len(string)