📜  Python字符串长度 | len()(1)

📅  最后修改于: 2023-12-03 15:04:38.932000             🧑  作者: Mango

Python字符串长度 | len()

在Python中,字符串是一种不可变且有序的数据类型,用于表示文本信息。len()函数是Python的内置函数之一,用于获取字符串的长度。

语法
len(string)
参数
  • string: 要获取长度的字符串。
返回值

len()函数返回指定字符串的字符个数。

示例

下面是一些使用len()函数获取字符串长度的示例:

string1 = "Hello, World!"
length1 = len(string1)
print(f"The length of '{string1}' is {length1}.")

string2 = "你好,世界!"
length2 = len(string2)
print(f"The length of '{string2}' is {length2}.")

string3 = ""
length3 = len(string3)
print(f"The length of an empty string is {length3}.")

输出结果如下:

The length of 'Hello, World!' is 13.
The length of '你好,世界!' is 7.
The length of an empty string is 0.
注意事项
  • len()函数返回的是字符串中字符的个数,包括空格和特殊字符。
  • 对于包含非ASCII字符的字符串,每个非ASCII字符(如汉字)都会计算为一个字符。
  • 当字符串为空时,len()函数返回0。

通过len()函数,程序员可以方便地获取字符串的长度,对于需要统计字符数量的任务非常有用。