[英]how to count characters in a string in python?
I created a function that would count the number of characters in a string with this code:我创建了一个函数,可以使用以下代码计算字符串中的字符数:
def count_characters_in_string(mystring):
s=0
x=mystring
for i in x:
t=i.split()
s=s+len(t)
print("The number of characters in this string is:",s)
count_characters_in_string("Apple")
This is what it returns: The number of characters in this string is: 1 The number of characters in this string is: 2 The number of characters in this string is: 3 The number of characters in this string is: 4 The number of characters in this string is: 5这是它返回的内容: 该字符串中的字符数为:1 该字符串中的字符数为:2 该字符串中的字符数为:3 该字符串中的字符数为:4 字符数在这个字符串中是:5
Is there a way to only print the last line so that it prints:有没有办法只打印最后一行,以便打印:
The number of characters in this string is: 5此字符串中的字符数为:5
you can just use:你可以使用:
len(mystring)
in your code, to print only the last line you can use:在您的代码中,仅打印您可以使用的最后一行:
for i in x:
s += 1
print("The number of characters in this string is:",s)
In python string can be seen as a list u can just take its lenght在 python 中,字符串可以看作是一个列表,你可以取它的长度
def count_characters_in_string(word):
return len(word)
Use this:用这个:
def count_characters_in_string(input_string)
letter_count = 0
for char in input_string:
if char.isalpha():
letter_count += 1
print("The number of characters in this string is:", letter_count)
When you run:当你运行时:
count_characters_in_string("Apple Banana")
It'll output:它会输出:
"The number of characters in this string is: 11"
This should work.这应该有效。
def count_characters_in_string(mystring):
s=0
x=mystring
for i in x:
t=i.split()
s=s+len(t)
print("The number of characters in this string is:",s)
count_characters_in_string("Apple")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.