문자열에 존재하는 단어와 문자의 수를 계산해야 하는 경우,
아래는 동일한 데모입니다.
예시
my_string = "Hi there, how are you Will ? "
print("The string is :")
print(my_string)
my_chars=0
my_words=1
for i in my_string:
my_chars=my_chars+1
if(i==' '):
my_words=my_words+1
print("The number of words in the string are :")
print(my_words)
print("The number of characters in the string are :")
print(my_chars) 출력
The string is : Hi there, how are you Will ? The number of words in the string are : 8 The number of characters in the string are : 29
설명
-
문자열이 정의되고 콘솔에 표시됩니다.
-
문자 수는 0에 할당됩니다.
-
단어 수는 1에 할당됩니다.
-
문자열이 반복되고 문자 변수가 증가합니다.
-
공백이 있으면 단어 수도 증가합니다.
-
이 값은 콘솔에 표시됩니다.