Home>Article>Backend Development> How to get the length of a string in python
How to get the length of a string in python? This article will introduce you to 4 methods of calculating and outputting the length of a string in python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Strings in Python are immutable sequences of Unicode code points. Given a string, we can find its length. Example:
Input: 'Hello world! '
Output: 5
Input: 'Hello!'
Output: 5
Now we will introduce 4 ways to calculate the length of a string in python and output the length. [Recommended related video tutorials:Python Tutorial]
1. Use Python’s built-in function len()
Python The built-in function len() can return the number of items in the container. We can use len() to count and return the length of the string, for example:
# 获取并输出字符串长度 #使用 len() str = "hello world !" print(len(str))
Run:
2. Use for loops and operators
can iterate strings directly in the for loop. Keep a count of the number of iterations and output the length of the string at the end.
# 使用for循环 # 返回字符串长度 def findLen(str): counter = 0 for i in str: counter += 1 return counter str = "hello !" print(findLen(str))
Run:
3. Use while loop and slice (Slice)
We first slice a string so that it is shortened by 1 at each iteration, which will eventually produce an empty string, at which time the while loop also stops. Keep a count of the number of iterations and finally output the length of the string.
# 使用 while 循环. # 返回字符串长度 def findLen(str): counter = 0 while str[counter:]: counter += 1 return counter str = "while 循环" print(findLen(str))
Running result:
4. Use the join() method and count() method of string
The string join method uses iteration and returns a string, which is the concatenation of the strings in the iteration. The delimiter between elements is the original string on which the method was called. Using join() and count() in the original string to connect strings can also determine and output the length of the string.
# 使用 join 和 count 方法 # 返回字符串长度 def findLen(str): if not str: return 0 else: some_random_str = 'py' return ((some_random_str).join(str)).count(some_random_str) + 1 str = "geeks" print(findLen(str))
Run and output:
Summary:The above is the entire content of this article, I hope it can be helpful to everyone learning helps.
The above is the detailed content of How to get the length of a string in python. For more information, please follow other related articles on the PHP Chinese website!