为什么在我尝试后我的其中一个字符串会一遍又一遍地重复

Why does one of my strings get repeated over and over again after I try

我正在尝试将各种字符串连接在一起以形成一条消息。

理想的输出是这样的:

The following stocks have changed with more than 0.9%:\
MSFT: 0.05\
TSLA: 0.012\
AAPL: 0.019

下面是我的代码:

stocks = {
    "MSFT":0.05,
    "TSLA":0.012,
    "AAPL":0.019,
}

subject = 'Opening Price Warnings'
body = 'The following stocks have changed with more than 0.9%: \n'.join([f'{key}: {value}' for key, value in stocks.items()])
msg = f'Subject: {subject}\n\n{body}'
print(msg)

我的代码一遍又一遍地重复第一行。
我收到这样的消息:\

MSFT: 0.05The following stocks have changed with more than 0.9%:\
TSLA: 0.012The following stocks have changed with more than 0.9%:\
AAPL: 0.019The following stocks have changed with more than 0.9%:

为什么会这样?

因为在 body 中,您将 相同的 初始字符串加入到 all for 循环字符串的条目中。

只有 body = 'The following stocks have changed with more than 0.9%: 并创建一个 new 字符串,其中只有 dict 元素。

stocks = {'MSFT': 0.05, 'TSLA': 0.012}
body1 = 'The following stocks have changed with more than 0.9%: \n'
body2 = '\n'.join([f'{key}: {value}' for key, value in stocks.items()])
body1 + body2
# 'The following stocks have changed with more than 0.9%: \nMSFT: 0.05\nTSLA: 0.012\nAAPL: 0.019'

str.join()NOT 一个连接两个字符串的函数。

join函数用于插入分隔符。
分隔符分隔字符串容器中的元素。

示例如下:

eldest_cookie_jar = [
    "red",
    "blue",
    "green"
]

s = "-".join(eldest_cookie_jar)
print(s)

控制台输出为:

red-blue-green

在上面的示例中,我使用连字符 (-) 作为分隔符。
所有颜色都用连字符分隔。

模式是:

output = delimiter.join(non_delimiters)

非定界符 是字符串形式的实际数据。

如果您希望数字之间用逗号分隔,则将数字转换为字符串,然后调用 str.join(),如下所示:

stryng = ",".join(numbers)     

如果你想象制作一个三明治,那么我们有:

buns = ["(top bun)", "(bottom bun)"]
meat = "(meat)"

result = meat.join(buns)
print(result)
# "(top bun)(meat)(bottom bun)"

下面还有更多例子;包括在内是为了非常详尽:

eldest_cookie_jar = [
    "red",
    "blue",
    "green"
]

# It is important to convert data to strings
# before using `str.join()` to delimit the data
#
# `map(str, data)` will convert each element
# of `data` into a string.
#

youngest_cookie_jar = tuple(map(str, [0.1, 0.2, 0.3]))

meta_container = [
    eldest_cookie_jar,
    youngest_cookie_jar
]

delims = [
    ", ",
    "...",
    ":--:",
    " ",
    "   ¯\_(ツ)_/¯   "
]

for container in meta_container:
    for delimiter in delims:
        result = delimiter.join(container)
        beginning = "\n----------\n"
        print(result, end=beginning)

控制台输出为:

red, blue, green
----------
red...blue...green
----------
red:--:blue:--:green
----------
red blue green
----------
red   ¯\_(ツ)_/¯   blue   ¯\_(ツ)_/¯   green
----------
0.1, 0.2, 0.3
----------
0.1...0.2...0.3
----------
0.1:--:0.2:--:0.3
----------
0.1 0.2 0.3
----------
0.1   ¯\_(ツ)_/¯   0.2   ¯\_(ツ)_/¯   0.3
----------