w3resource

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


String Formatter with Length Limit

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

For more Practice: Solve these Related Problems:

  • Write a Python program to format a string to a fixed width by padding it with spaces.
  • Write a Python program to truncate a string that exceeds a given length.
  • Write a Python program to center a string within a specified width using special characters.
  • Write a Python program to replace excess whitespace in a string with a single space.

Go to:


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.

Python Code Editor:

 

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.