【Python】\n , \t , title() ,lstrip() ,strip() ,removeprefix() 

【Python】\n , \t , title() ,lstrip() ,strip() ,removeprefix() 


# Initialize a string with newlines and tabs
text = "\n\tHello World!\n\tThis is a new line.\n\t\tThis is indented."

# Show the original text with escape characters
print("Original Text:")
print("--------------")
print(repr(text))

# Convert the first letter of each word to uppercase using title()
title_text = text.title()
print("\nTitle Text:")
print("-----------")
print(title_text)

# Remove leading whitespaces (newlines and tabs) using lstrip()
lstrip_text = title_text.lstrip()
print("\nLStrip Text:")
print("------------")
print(lstrip_text)

# Remove both leading and trailing whitespaces (newlines and tabs) using strip()
strip_text = title_text.strip()
print("\nStrip Text:")
print("-----------")
print(strip_text)

# Remove a specific prefix using removeprefix()
# The 'Hello ' prefix is present at the beginning of the lstrip_text,
# so it can be removed successfully
removeprefix_text = lstrip_text.removeprefix("Hello ")
print("\nRemovePrefix Text:")
print("-----------------")
print(removeprefix_text)



Original Text:
--------------
'\n\tHello World!\n\tThis is a new line.\n\t\tThis is indented.'

Title Text:
-----------

	Hello World!
	This Is A New Line.
		This Is Indented.

LStrip Text:
------------
Hello World!
	This Is A New Line.
		This Is Indented.

Strip Text:
-----------
Hello World!
	This Is A New Line.
		This Is Indented.

RemovePrefix Text:
-----------------
World!
	This Is A New Line.
		This Is Indented.

repr(text): Shows the original text with escape characters (\n for new lines, \t for tabs).
title(): Converts the first character of each word to uppercase.
lstrip(): Removes any leading whitespace characters like spaces, tabs (\t), and newlines (\n).
strip(): Removes both leading and trailing whitespace characters.
removeprefix(): Removes a specific prefix from the beginning of the string, if present.

張貼留言

0 留言