Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Iterate over characters of a string in Python
Next article icon

Count the number of characters in a String – Python

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The goal here is to count the number of characters in a string, which involves determining the total length of the string. For example, given a string like “GeeksForGeeks”, we want to calculate how many characters it contains. Let’s explore different approaches to accomplish this.

Using len()

len() is a built-in method that returns the number of elements in a sequence, such as a string. It directly accesses the internal length attribute of the string, making it the most efficient way to count characters.

[GFGTABS]
Python

s = "GeeksForGeeks"  res = len(s) print(res) 


[/GFGTABS]

Output
13 

Explanation: len() returns the length of the string (13 in this case) and assigns it to the variable res, which is then printed.

Using generator expression

Generator expression like sum(1 for _ in s) creates a lazy iterator that yields 1 for each character. The sum() function then adds these 1s, giving the total character count. This method is Pythonic, clean and allows for easy filtering to customize the counting.

[GFGTABS]
Python

s = "Geeks for Geeks!"  res = sum(1 for _ in s) print(res) 


[/GFGTABS]

Output
16 

Explanation: sum(1 for _ in s) count the characters in the string s. For each character in the string, it yields 1 and the sum() function adds these 1s together.

Using for loop

This method manually loops through each character in the string, incrementing a counter by 1. It’s simple, readable and easy to modify for more complex logic like conditional counting.

[GFGTABS]
Python

s = "Geeks for Geeks!" count = 0 for char in s:     if char != ' ':         count += 1  print(count) 


[/GFGTABS]

Output
14 

Explanation: This code initializes count to 0 and iterates over each character in s. If the character is not a space (char != ‘ ‘), count is incremented. After the loop, count contains the total number of non-space characters in the string.

Using reduce()

reduce() function from functools module applies a function cumulatively to items in a sequence. You can use it to count characters by accumulating 1 for each character, but it’s less readable and efficient than loops or built-in functions due to function call overhead.

[GFGTABS]
Python

from functools import reduce  s = "GeeksForGeeks" res = reduce(lambda acc, _: acc + 1, s, 0) print(res) 


[/GFGTABS]

Output
13 

Explanation: This code uses reduce() with a lambda function to increment an accumulator for each character in s, starting from 0. After processing all characters, it returns and prints the total count.

Related Articles:

  • string
  • len()
  • Generator expression
  • loops
  • reduce()
  • functools module


Next Article
Iterate over characters of a string in Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Get Last N characters of a string - Python
    We are given a string and our task is to extract the last N characters from it. For example, if we have a string s = "geeks" and n = 2, then the output will be "ks". Let's explore the most efficient methods to achieve this in Python. Using String Slicing String slicing is the fastest and most straig
    2 min read
  • Iterate over characters of a string in Python
    In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Let’s explore this approach. Using for loopThe simplest way to iterate over the characters in
    2 min read
  • Python - Check if String contains any Number
    We are given a string and our task is to check whether it contains any numeric digits (0-9). For example, consider the following string: s = "Hello123" since it contains digits (1, 2, 3), the output should be True while on the other hand, for s = "HelloWorld" since it has no digits the output should
    2 min read
  • Frequency of Numbers in String - Python
    We are given a string and we have to determine how many numeric characters (digits) are present in the given string. For example: "Hello123World456" has 6 numeric characters (1, 2, 3, 4, 5, 6). Using re.findall() re.findall() function from the re module is a powerful tool that can be used to match s
    3 min read
  • Python - Test if String contains any Uppercase character
    The goal is to check if a given string contains at least one uppercase letter (A-Z). Using any() and isupper()any() function, combined with isdigit(), checks if any character in a string is a digit. It efficiently scans the string and returns True if at least one digit is found. [GFGTABS] Python # D
    3 min read
  • Python Program to Count the Number of Vowels in a String
    In this article, we will be focusing on how to print each word of a sentence along with the number of vowels in each word using Python. Vowels in the English language are: 'a', 'e', 'i', 'o', 'u'. So our task is to calculate how many vowels are present in each word of a sentence. So let us first des
    10 min read
  • Check if string contains character - Python
    We are given a string and our task is to check if it contains a specific character, this can happen when validating input or searching for a pattern. For example, if we check whether 'e' is in the string 'hello', the output will be True. Using in Operatorin operator is the easiest way to check if a
    2 min read
  • Python - Least Frequent Character in String
    The task is to find the least frequent character in a string, we count how many times each character appears and pick the one with the lowest count. Using collections.CounterThe most efficient way to do this is by using collections.Counter which counts character frequencies in one go and makes it ea
    3 min read
  • Python | Longest Run of given Character in String
    Sometimes, while working with Strings, we can have a problem in which we need to perform the extraction of length of longest consecution of certain letter. This can have application in web development and competitive programming. Lets discuss certain ways in which this task can be performed. Method
    6 min read
  • Python program to count the number of spaces in string
    In Python, there are various ways to Count the number of spaces in a String. Using count() Methodcount() method in Python is used to return the number of occurrences of a specified element in a list or string [GFGTABS] Python s = "Count the spaces in this string." # Count spaces using the
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences