Remember
expandtabs() replaces tabs with spaces up to the next tab stop. The number of inserted spaces depends on the current column.
expandtabs() replaces tabs with spaces up to the next tab stop. The number of inserted spaces depends on the current column.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
text = 'a\tb'
result = text.expandtabs(4)
print(result)Top-level scope
'a\tb'Object 2 · str'a b'expandtabs() replaces tabs with spaces up to the next tab stop. The number of inserted spaces depends on the current column.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
text = 'a\tb'
result = text.expandtabs(4)
print(result)
|
v
DISPLAYED RESULT
a b
FINAL BINDINGS
text --> object 1 (str)
result --> object 2 (str)
object 1: 'a\tb'
object 2: 'a b'Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
text = 'a\tb'
result = text.expandtabs(4)
print(result)Top-level scope
'a\tb'Object 2 · str'a b'The example has finished. Compare the final output with the values and references above.
a b
What do you expect this program to print?
text = 'a\tb'
result = text.expandtabs(4)
print(result)expandtabs() MethodThe expandtabs() method in Python is used with string objects. It replaces all tab characters (\t) in a string with spaces. You can also set the number of spaces a tab should expand to.
string.expandtabs(tabsize=8)
tabsize – (Optional) The number of spaces to replace each \t with. Default is 8.\t tab characters are replaced with spaces.text = "Python\tRocks!"
print(text.expandtabs())
Python Rocks!
text = "A\tB\tC"
print(text.expandtabs(4))
A B C
data = "Name\tAge\tCity"
print(data.expandtabs(10))
Name Age City
expandtabs() doesn’t modify the original string (strings are immutable)This method might come up in string formatting problems where you need to normalize or align data.
expandtabs() replaces \t with spaces8, but you can customize itWrite a Python program that takes a tab-separated string from user input and prints the expanded version using 6 spaces per tab.
user_input = input("Enter a tab-separated string: ")
print(user_input.expandtabs(6))
Connect what you noticed in the example with the idea below.
expandtabs() replaces tabs with spaces up to the next tab stop. The number of inserted spaces depends on the current column.
expandtabs(4) always inserts exactly four spaces per tab.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.