为什么我的一根弦在我尝试后会一次又一次地重复



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

理想的输出如下:

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}nn{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中,您将相同的初始字符串连接到for循环字符串的所有条目。

只需要body = 'The following stocks have changed with more than 0.9%:,并制作一个只有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.05nTSLA: 0.012nAAPL: 0.019'

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

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
----------

相关内容

最新更新