Change language

Python | Repeat line up to K

|

Method # 1: Using List Slicing and // operator

This task can be accomplished using the above tools. In this case, we simply multiply the string until it is greater than or equal to K, and then simply omit some of the extra string using the list slicing method.

# Python3 demo code
# Repeat line up to K
# using list slicing and // statement

 
# initialization string

test_string = "GeeksforGeeks"

 
# initialization K

K = 30

 
# print original new line

print ( "The original string: " + str (test_string))

 
# using list slicing and // operator
# Repeat line up to K

res = (test_string * (K / / len (test_string) + 1 )) [: K]

 
# print result

print (  "String after performing repeatition:" + res)

Output:

 The original string: Python.Engineering String after performing repeatition: GeeksforGeeksGeeksforGeeksGeek 

Method # 2: Using divmod () + slicing the list

The division used in the above method is can be replaced in this method with the divmod function, which improves the readability of the code at a cost of 40% performance penalty.

# Python3 code for demos
# Repeat line up to K
# using divmod () + slice the list

 
# initializing with string

test_string = "GeeksforGeeks"

 
# initializing K

K = 30

  
# print original line

print ( "The original string:" + str (test_string))

 
# using divmod () + slice the list
# Repeat line up to K

div, mod = divmod (K, len (test_string))

res = test_string * div + test_string [: mod]

 
# print result

print ( "String after performing repeatition:" + res)

Output:

 The original string: Python.Engineering String after performing repeatition : GeeksforGeeksGeeksforGeeksGeek 

Python | Repeat line up to K Python functions: Questions

Python | Repeat line up to K 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