拼接字符串
# 定义常量(全大写命名)
BASE_URL = "https://api.example.com/v1/"
FILE_PATH = "/data/user/"
# 引用常量拼接字符串
user_id = "123"
full_url = BASE_URL + "users/" + user_id # 使用加号拼接
print(full_url) # 输出: https://api.example.com/v1/users/123
# 使用 f-string 格式化(推荐)
full_url_f = f"{BASE_URL}users/{user_id}"
print(full_url_f) # 输出: https://api.example.com/v1/users/123
# 使用 format 方法
full_url_format = "{base}users/{id}".format(base=BASE_URL, id=user_id)
print(full_url_format) # 输出: https://api.example.com/v1/users/123
# 拼接文件路径
file_name = "profile.txt"
full_file_path = FILE_PATH + file_name
print(full_file_path) # 输出: /data/user/profile.txt