在这个Python程序中,我们需要检查字符串的长度,所以我们需要知道Python中的字符串是什么。字符串是字母或字符的序列,我们需要找到它的长度。为此,我们必须使用一个计数器,当我们遍历字符串的每个字符时,该计数器将递增一。
从用户接受字符串后,我们将其存储在一个变量中。然后使用Python程序中的for循环直到字符串的末尾。使用变量count在每次循环迭代中递增。最后,打印计数器的值。在Python中,我们不需要在for loop中初始化变量。让我们来分解代码。
第一步:我们使用Python编程中的input函数从用户那里接受字符串并将其存储在一个变量中。
第二步:将计数器初始化为零;此计数器用于在遍历字符串时递增值。
第三步:使用for loop直到字符串的末尾。
第四步:每次我们在for loop内部移动直到字符串结束时,将计数器递增一。
第五步:使用Python语言中的print函数打印计数器的值作为字符串的长度。
str = input("Enter any string: ")
count = 0 # initialize the counter to zero
for s in str: # Use a for loop till the string ends.
count = count + 1 # increment the counter by 1 every time control gets inside the for loop
print("Length of the string is:", count)
Enter any string : Hello Length of the string is: 5