f-Strings (Recommended)
## Modern f-string formatting
student = ('John Doe', 25, 'Computer Science')
print(f"Name: {student[0]}, Age: {student[1]}, Major: {student[2]}")
## Traditional .format() method
student = ('John Doe', 25, 'Computer Science')
print("Name: {}, Age: {}, Major: {}".format(student[0], student[1], student[2]))
graph TD
A[Tuple Formatting] --> B[String Interpolation]
A --> C[Alignment]
A --> D[Type Conversion]
A --> E[Padding]
Alignment and Padding
## Formatting with alignment and padding
data = ('Python', 3.14, 42)
print(f"{'Language':>10}: {data[0]}")
print(f"{'Pi':>10}: {data[1]}")
print(f"{'Number':>10}: {data[2]}")
Technique |
Description |
Example |
Width Specification |
Control field width |
f"{value:10}" |
Precision |
Limit decimal places |
f"{value:.2f}" |
Type Conversion |
Change display format |
f"{value!r}" |
Tuple to String Conversion
Using join() Method
## Converting tuple to formatted string
fruits = ('apple', 'banana', 'cherry')
formatted_fruits = ', '.join(fruits)
print(f"Fruits: {formatted_fruits}")
## Complex formatting in LabEx
data_tuple = ('LabEx', 2023, 3.14159)
print(f"""
Platform: {data_tuple[0]}
Year: {data_tuple[1]}
Constant: {data_tuple[2]:.2f}
""")
## Handling formatting errors
try:
mixed_tuple = (42, 'hello', 3.14)
print(f"Integer: {mixed_tuple[0]}, String: {mixed_tuple[1]}")
except IndexError:
print("Tuple index out of range")
except TypeError:
print("Formatting error occurred")
## Conditional formatting with tuples
scores = (85, 92, 78)
formatted_scores = [f"{'Pass' if score >= 80 else 'Fail'}: {score}" for score in scores]
print("\n".join(formatted_scores))
By mastering these formatting techniques, you'll be able to present tuple data in clear, readable, and flexible ways.