[英]how to count characters in a string in python?
我創建了一個函數,可以使用以下代碼計算字符串中的字符數:
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")
這是它返回的內容: 該字符串中的字符數為:1 該字符串中的字符數為:2 該字符串中的字符數為:3 該字符串中的字符數為:4 字符數在這個字符串中是:5
有沒有辦法只打印最后一行,以便打印:
此字符串中的字符數為:5
你可以使用:
len(mystring)
在您的代碼中,僅打印您可以使用的最后一行:
for i in x:
s += 1
print("The number of characters in this string is:",s)
在 python 中,字符串可以看作是一個列表,你可以取它的長度
def count_characters_in_string(word):
return len(word)
用這個:
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)
當你運行時:
count_characters_in_string("Apple Banana")
它會輸出:
"The number of characters in this string is: 11"
這應該有效。
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.