How would I find the amount of characters in a string and then use that to print a certain amount of some character that you choose. For example:

a = 'string' # this holds 6 characters
print '*' * # amount of characters in string

Dani AI

Generated

As noted, Python provides a built-in way to get a string's length: use len() on the variable that holds the text. That numeric result can then be used to produce a repeated symbol or to control a loop — no manual counting required. This expands on the quick reply and shows a couple of practical, slightly more robust approaches.

def repeat_char(text, ch):
    n = len(text)
    return ch * n

print(repeat_char("string", "*"))   # prints six asterisks

A few important caveats and tips that matter if this code is used later or on non-ASCII text:

  • In Python 3 str is Unicode and len() returns code points. For most simple ASCII text this matches "characters", but it can differ for composed characters (e.g., e + combining accent) and some emoji sequences.
  • To count user-visible characters (grapheme clusters) reliably, use the third‑party regex module and its \X token:
# pip install regex
import regex

def grapheme_count(s):
    return len(regex.findall(r"\X", s))
  • To count bytes instead of characters (useful when sending data over a network), use len(s.encode("utf-8")).
  • To count only non-space characters, use a generator expression: sum(1 for ch in s if not ch.isspace()).

This keeps the original, simple solution intact while addressing edge cases that often surprise people returning to strings after a break (as mentioned).

Recommended Answers

All 2 Replies

Perhaps you mean

>>> len('string')
6

Thanks I have not been doing much work with strings latley I feel stupid now. Thanks for helping me though

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.