擅长:python、mysql、java
<p>您可能需要初始化变量<code>j</code>(在重命名的<code>counter</code>下):</p>
<pre><code>def string_length(my_string):
"""returns the length of a string
"""
counter = 0
for char in my_string:
counter += 1
return counter
# taking user input
string_input = input("enter string :")
length = string_length(string_input)
print("length is ", length)
</code></pre>
<p>这也可以用生成器表达式在一行“pythonic”中完成,zondo指出:</p>
<pre><code>def string_length(my_string):
"""returns the length of a string
"""
return sum(1 for _ in my_string)
</code></pre>