在Python中使用len()查找字符串的长度

Python-len()函数

len() function是Python中的内置函数,用于查找给定字符串的长度,它以string为参数并返回其长度。

注意:在此程序中,我们len()用于获取给定字符串的长度,但len()也可以用于其他目的,例如查找列表中元素的总数等。

语法:

len(string)

示例

    Input: "Hello"
    Output: 5

    Input: "Hello world"
    Output: 11

Python-源代码

#定义两个字符串
str1 = "Hello"
str2 = "Hello World"

#字符串的打印长度
print "Length of str1: ", len(str1)
print "Length of str2: ", len(str2)

#直接字符串值的打印长度
print "Length of \"NHOOO\": ", len("NHOOO")

输出结果

$python main.py
Length of str1:  5
Length of str2:  11
Length of "NHOOO":  11

在不使用消息的情况下打印长度

#定义两个字符串
str1 = "Hello"
str2 = "Hello World"

#字符串的打印长度
print(len(str1))
print(len(str2))

#直接字符串值的打印长度
print(len("NHOOO"))

输出结果

$python main.py
5
11
11