带 f 字符串的字典的字符串格式
String format for dictionary with f-strings
我有一本字典,我想以 f-strings 格式打印它的键和值。
示例 1:
dic = {'A': 1, 'B': 2}
Output: "This is output A:1 B:2"
示例 2:
dic = {'A': 1, 'B': 2, 'C': 3}
Output: "This is output A:1 B:2 C:3"
我想请求一个通用的答案,以便我可以添加更多的键值对。
您可以遍历键值对,并相应地打印输出:
dic = {'A': 1, 'B': 2, 'C': 3}
print('This is output', end=' ')
for k,v in dic.items():
print(str(k) + ':' + str(v), end=' ')
输出
This is output A:1 B:2 C:3
或者您可以连接字符串(相同的输出):
dic = {'A': 1, 'B': 2, 'C': 3}
s = ''
for k,v in dic.items():
s += f'{k}:{v} ' #thanks to @blueteeth
print('This is output', s.strip())
尝试加入()
'This is output ' + ' '.join(f'{key}:{value}' for key, value in dic.items())
这就是你需要的-
d = {"A": 1, "B": 2, "C": 3}
print("This is output ")
for key, value in d.items():
print(f"{key}:{value}", end=" ")
我有一本字典,我想以 f-strings 格式打印它的键和值。
示例 1:
dic = {'A': 1, 'B': 2}
Output: "This is output A:1 B:2"
示例 2:
dic = {'A': 1, 'B': 2, 'C': 3}
Output: "This is output A:1 B:2 C:3"
我想请求一个通用的答案,以便我可以添加更多的键值对。
您可以遍历键值对,并相应地打印输出:
dic = {'A': 1, 'B': 2, 'C': 3}
print('This is output', end=' ')
for k,v in dic.items():
print(str(k) + ':' + str(v), end=' ')
输出
This is output A:1 B:2 C:3
或者您可以连接字符串(相同的输出):
dic = {'A': 1, 'B': 2, 'C': 3}
s = ''
for k,v in dic.items():
s += f'{k}:{v} ' #thanks to @blueteeth
print('This is output', s.strip())
尝试加入()
'This is output ' + ' '.join(f'{key}:{value}' for key, value in dic.items())
这就是你需要的-
d = {"A": 1, "B": 2, "C": 3}
print("This is output ")
for key, value in d.items():
print(f"{key}:{value}", end=" ")