w3resource

Python: Format a specified string limiting the length of a string

Python Basic: Exercise-120 with Solution

Write a Python program to format a specified string limiting the length of a string.

Sample Solution:

Python Code:

str_num = "1234567890"
print("Original string:",str_num)
print('%.6s' % str_num)
print('%.9s' % str_num)
print('%.10s' % str_num)

Sample Output:

Original string: 1234567890
123456
123456789
1234567890

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to round a floating-point number to specified number decimal places.
Next: Write a Python program to determine if variable is defined or not.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Unpack variables from iterable:

# One can unpack all iterables (tuples, list etc)
>>> a, b, c = 1, 2, 3
>>> a, b, c
(1, 2, 3)

>>> a, b, c = [1, 2, 3]
>>> a, b, c
(1, 2, 3)