Change language

A way to repeat a string up to a specific length in Python?

|

If you want the string to repeat up to n characters, then you can first repeat the entire string up to n / len (s) times and add n% len (s) characters at the end. For example,

 def repeat_n (string, n): l = len (s) full_rep = n / l # Construct string with full repetitions ans = ’’ .join (string for i in xrange (full_rep)) # add the string with remaining characters at the end. return ans + string [: n% l] repeat_n (’asdf’, 10) 

This will give the output:



 ’asdfasdfas’ 

You can also use the operation & # 8216; * & # 8217; for a line to repeat the line. For example,


< pre class = "EnlighterJSRAW" data-enlighter-language = "python"> def repeat_n (string_to_expand, n): return (string_to_expand * ((n / len (string_to_expand)) + 1)) [: n] repeat_n (’asdf’, 10)

This will give the output:

 ’asdfasdfas’ 



 

A way to repeat a string up to a specific length in Python? Python functions: Questions

A way to repeat a string up to a specific length in Python? repeat: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method