[英]Why does this Python code just print one of the variables over and over again?
[英]Why does one of my strings get repeated over and over again after I try
我正在嘗試將各種字符串連接在一起以形成一條消息。
理想的 output 如下所示:
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
中,您將相同的初始字符串連接到 for 循環字符串的所有條目。
have just 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.05\nTSLA: 0.012\nAAPL: 0.019'
str.join()
不是連接兩個字符串的 function 。
join
function 用於插入分隔符。
分隔符分隔字符串容器中的元素。
一個例子如下所示:
eldest_cookie_jar = [
"red",
"blue",
"green"
]
s = "-".join(eldest_cookie_jar)
print(s)
控制台 output 是:
red-blue-green
在上面的示例中,我使用連字符 ( -
) 作為分隔符。
所有 colors 都用連字符分隔。
模式是:
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)
控制台 output 是:
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
----------
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.