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 and limit the length of a string.

Sample Solution:

Python Code:

# Define a string containing a numeric value.
str_num = "1234567890"

# Print the original string.
print("Original string:", str_num)

# Print the first 6 characters of the string.
print('%.6s' % str_num)

# Print the first 9 characters of the string.
print('%.9s' % str_num)

# Print the entire string (first 10 characters) as it is.
print('%.10s' % str_num)

Sample Output:

Original string: 1234567890
123456
123456789
1234567890

Python Code Editor:

 

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 Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/python-basic-exercise-120.php