如何添加破折号(分隔响应)

2024-10-17 06:27:06 发布

您现在位置:Python中文网/ 问答频道 /正文

最终的结果是捆绑在一起的,它需要分开

这是我的密码:

a = input('Clubhouse location: ')

for char in a:
  code = str(ord(char))
  b = a.replace(a, code)
  print(b, end='')

以下是我的结果:

Clubhouse location: Treehouse
84114101101104111117115101

以下是它应该是什么:

Clubhouse location: Treehouse
84-114-101-101-104-111-117-115-101

Tags: in密码forinputcodelocationreplaceend
3条回答

只需使用-(如果char不是字符串中的最后一个a)作为print函数的结束参数:

a = input('Clubhouse location: ')

for i, char in enumerate(a):
  code = str(ord(char))
  b = a.replace(a, code)
  end = '-' if i < len(a) - 1 else ''
  print(b, end = end)

您可以使用^{}

a = input('Clubhouse location: ')
print('-'.join(str(ord(ch)) for ch in a))

您还可以将unpack字符码转换成print()并使用^{}参数:

print(*(ord(ch) for ch in a), sep='-')

使用str.join

例如:

a = input('Clubhouse location: ')

print("-".join(str(ord(char)) for char in a))
#  > 84-114-101-101-104-111-117-115-101

相关问题 更多 >