Python String Operations and Formatting

String Definition Methods

Python provides three distinct approaches to define string variables:

① Double Quotation Method

message_1="This is a string value"
print(message_1)

Output:
This is a string value

② Single Quotation Method

message_2='This is also a string value'
print(message_2)

Output:
This is also a string value

③ Triple Quotation Method
This method defines a string spanning multiple lines. When assigned to a variable, it functions as a multi-line string. When not assigned, it serves as a multi-line comment.

text_3="""I am also a string value"""
text_4"""
Within the triple quotation boundaries
everything is considered
string data
"""
print(text_3)
print(text_4)

Output:
I am also a string value
Within the triple quotation boundaries
everything is considered
string data

String Quotation Nesting

When your string needs to contain quotation marks, you have several options:

① Single quotes can contain double quotes

quotation='"Welcome"'
print(quotation)

Output:
"Welcome"

② Double quotes can contain single quotes

quotation="'Welcome'"
print(quotation)

Output:
'Welcome'

③ Escape characters can be used to neutralize quotation marks

quotation='\'Welcome\''
print(quotation)
quotation="\"Welcome\""
print(quotation)

Output:
'Welcome'
"Welcome"

String Concatenation

The "+" operator can be used to join string variables or literals.

① Concatenating string literals

print("My name is "+"Alex")

Output:
My name is Alex

② Concatenating literals with variables

first_name="Alex"
location="123 Main Street"
print("I am "+first_name+", residing at "+location)

Output:
I am Alex, residing at 123 Main Street

Note: Strings cannot be directly concatenated with non-string types due to type incompatibility.

String Formatting

String concatenation has limitations:

  • Becomes cumbersome with many variables
  • Cannot be used with non-string types

String formatting provides an alternative that handles these issues: String formatting in Python replaces placeholders in a string with specific values or expressions.

① Formatting Method 1: % Operator
Common placeholders:

Using %s as an example:

  • % indicates: I'm creating a placeholder
  • s indicates: convert the variable to a string and place it in the position

Syntax: "%placeholder" % variable

interest="reading"
info="My hobby is %s" % interest
print(info)

Output:
My hobby is reading

For multiple placeholders, variables must be enclosed in parentheses and placed in order:

user="Alex"
birth_year=1995
height=175.2
print("I am %s, born in %d, my height is %fcm"%(user,birth_year,height))

Output:
I am Alex, born in 1995, my height is 175.200000cm

Tips: When using %f for formatting, the default output includes six decimal places. In the example above, 175.2 becomes 175.200000.

② Formatting Method 2: f"{placeholder}"
Syntax: f"content{variable}"

  • Adding f before a string allows direct embedding of variables and expressions
  • {} marks the position where variable or expression values should be inserted

This method handles all data types without precision control, making it suitable for quick formatting when precision isn't required.

user="Alex"
birth_year=1995
height=175.2
print(f"I am {user}, born in {birth_year}, my height is {height}")

Output:
I am Alex, born in 1995, my height is 175.2

Precision Control in Formatting

Use "m.n" to control data width and precision.

  • m: Controls width (numeric, rarely used), doesn't work if set smaller than the number itself
  • .n: Controls decimal precision (numeric), rounds decimals

Examples:
%5d: Limits integer width to 5 characters.
For the number 11 with %5d, it becomes: [space][space][space]11, with three spaces padding.
%7.2f: Sets width to 7 and decimal precision to 2 (decimal point and decimals count toward width).
For 11.345 with %7.2f, the result is: [space][space]11.35 (two spaces padding, decimal part rounded to .35).
%.2f: No width limit, decimal precision set to 2. For 11.345 with %.2f, the result is 11.35.

# Precision control example
value1 = 11
value2 = 11.345
print("Number 11 with width 5: %5d" % value1)

# Width smaller than number doesn't take effect
print("Number 11 with width 1: %1d" % value1)

print("Number 11.345 with width 7 and precision 2: %7.2f" % value2)
print("Number 11.345 with precision 2 only: %.2f" % value2)

Output:
Number 11 with width 5: 11
Number 11 with width 1: 11
Number 11.345 with width 7 and precision 2: 11.35
Number 11.345 with precition 2 only: 11.35

Expression Formatting

An expression is a code statement with a clear result.
Examples:
1 + 1, 5 * 2, type("string") are expressions (results are numbers);
name = "John" and age = 10 + 10 are expressions on the right side of assignment (results asigned to variables).

Expression formatting can be done in two ways:

  1. f"{expression}"
  2. "%s%d%f" % (expression, expression, expression)

When you don't need to store data in variables, you can format expressions directly to simplify code.

print("1 + 2 equals: %d" % (1+2))
print(f"1 + 2 equals: {1 + 2}")
print("The type of number in Python is: %s" % type(42))

Output:
1 + 2 equals: 3
1 + 2 equals: 3
The type of number in Python is:

[Exercise] Stock Price Calculator
Given variables:
company_name, current stock price
stock_code, stock identifier
daily_growth_factor, daily growth rate (float)
growth_days, number of growth days
Calculate the final stock price after growth_days (final_price = current_price × growth_factor^growth_days). Use string formatting with 2 decimal places for floating point numbers.

company="TechCorp"
current_price=45.67
stock_code="TEC001"
growth_rate=1.15
days=30
final_price=current_price*growth_rate**days
print(f"Company: {company}, Stock Code: {stock_code}, Current Price: {current_price}")
print("Daily Growth Rate: %.1f, After %d days, stock price reached: %.2f" % (growth_rate, days, final_price))

Output:
Company: TechCorp, Stock Code: TEC001, Current Price: 45.67
Daily Growth Rate: 1.5, After 30 days, stock price reached: 897.32

Tags: python string-operations string-formatting f-strings string-concatenation

Posted on Wed, 02 Sep 2026 16:34:11 +0000 by Ameslee