Python Program to print different formats of string

Program

str = "Test String"
print("Printing the whole string:\t", format(str))
print("Printing first character of string:\t", format(str[0]))
print("Printing from 3rd char to 8th char:\t", format(str[3:8]))
print("Printing from 6th char till end of string:\t", format(str[6:]))
print("Printing from first till 2nd char:\t", format(str[:2]))

This program demonstrates various ways to access and format a string in Python.

str = "Test String"
  • A string variable str is initialized with "Test String".

print("Printing the whole string:\t", format(str))
  • Outputs the entire string using format(str).
  • Output: Printing the whole string: Test String
print("Printing first character of string:\t", format(str[0]))
  • Accesses the first character using str[0] (zero-based index).
  • Output: Printing first character of string: T
print("Printing from 3rd char to 8th char:\t", format(str[3:8]))
  • Extracts a substring using slicing str[3:8] (includes index 3 to 7).
  • Output: Printing from 3rd char to 8th char: t Str
print("Printing from 6th char till end of string:\t", format(str[6:]))
  • Extracts a substring from index 6 to the end using str[6:].
  • Output: Printing from 6th char till end of string: String
print("Printing from first till 2nd char:\t", format(str[:2]))
  • Extracts a substring from start to index 1 using str[:2].
  • Output: Printing from first till 2nd char: Te

Key Takeaways:

  1. String Indexing:

    • str[0] → Access the first character.
  2. String Slicing:

    • str[start:end] → Extracts a substring from start to end-1.
    • str[start:] → Extracts from start to the end.
    • str[:end] → Extracts from the beginning to end-1.
  3. The format() function is used to format output.

Output

Printing the whole string:	Test String
Printing first character of string:	T
Printing from 3rd char to 8th char:	t Str
Printing from 6th char till end of string:	tring
Printing from first till 2nd char:	Te