문자열은 일련의 유니코드 문자인 파이썬입니다. 한번 선언되면 변경할 수 없습니다. 이 기사에서는 문자열의 길이를 찾는 다양한 방법이 무엇인지 알아볼 것입니다.
len() 사용
이것은 가장 직접적인 방법입니다. 여기서 len()이라는 라이브러리 함수를 사용합니다. 문자열이 함수에 매개변수로 전달되고 화면에 문자 수가 표시됩니다.
예시
str ="Tutorials"
print("Length of the String is:", len(str)) 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
Length of the String is: 9
슬라이싱 사용
문자열 슬라이싱 방식을 사용하여 문자열에서 각 문자의 위치를 계산할 수 있습니다. 문자열의 위치 개수의 최종 개수가 문자열의 길이가 됩니다.
예시
str = "Tutorials"
position = 0
# Stop when all the positions are counted
while str[position:]:
position += 1
# Print the total number of positions
print("The total number of characters in the string: ",position) 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
The total number of characters in the string: 9
join() 및 count() 사용
join() 및 count() 문자열 함수도 사용할 수 있습니다.
예시
str = "Tutorials"
#iterate through each character of the string
# and count them
length=((str).join(str)).count(str) + 1
# Print the total number of positions
print("The total number of characters in the string: ",length) 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
The total number of characters in the string: 9