搜尋此網誌

2026年4月14日星期二

Strings in Python

In Python, you can concatenate strings using several methods: the + operator for simple joining, join() for efficiency with multiple strings, and formatted approaches like f-strings or format() for readability.

f"My number is: {5}"

F-strings (formatted string literals, introduced in Python 3.6) allow you to embed expressions directly inside a string.

Anything inside {} is evaluated as a Python expression, and its result is converted to a string.

In your case, {5} is just the literal integer 5. Python evaluates it, converts it to "5", and inserts it into the string.

literal: being the most basic meaning of a word or phrase, rather than an extended or poetic meaning

paragraph = """This is a paragraph. It can span multiple lines. No need for explicit newline characters.""" print(paragraph)

Output:

This is a paragraph. It can span multiple lines. No need for explicit newline characters.

In Python, the backslash (\) is an escape character. It signals that the next character has a special meaning or should be treated differently.

\n → newline

the text doesn't stop until it sees \'\'\'

Here, the backslashes are escaping the single quotes so Python doesn’t confuse them with the closing triple quotes. Without the backslashes, Python would think the string ended too early.

Microsoft Copilot

沒有留言:

發佈留言