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
Is there a way to only print the last line so that it prints:
The number of characters in this string is: 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
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.