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 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 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:
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. regex module and its \X token:# pip install regex
import regex
def grapheme_count(s):
return len(regex.findall(r"\X", s)) len(s.encode("utf-8")). 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).
Jump to Post— Gribouillis 1,391Perhaps you mean
>>> len('string') 6
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
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.