当我从我的类"r" var 打印 'chr(13)' 时

  • 本文关键字:chr 打印 var python-3.x
  • 更新时间 :
  • 英文 :


当我转到"print(ic.allopt)"时,我的allopt段中的chr(13)打印n而不是创建新行。当我从类中调用该变量时,我正在尝试打印一个新行。谢谢。

class Dialogue:
def __init__(self, seed, prompt, opt1, opt2, opt3, opt4):
self.id = seed
self.prompt = prompt
self.opt1 = opt1
self.opt2 = opt2
self.opt3 = opt3
self.opt4 = opt4
self.allopt = prompt, chr(13), "A)", opt1, "B)", opt2, "C)", opt3, "D)", opt4

openingscene = "hello weary traveller"
ic = Dialogue(1, "We came in and saw you on the ground, you looked pretty out of it, we tidied you up and tucked you "
"in. So. You have a name?", "My name is:", "Why do you want to know my name", "3", "4")

def initialclass():
print(openingscene)
print(ic.allopt)
initialclass()```

为了打印新行,您应该使用'n'chr(10)

您遇到的第二个问题是self.allopt是一个元组。为了打印元组的内容,您应该使用print(*ic.allopt)进行扩展或print("".join(ic.allopt))以创建字符串。

一般来说,我建议您使用 f 字符串阅读字符串格式。我发现这对您来说将是一个更好的解决方案。

发生的情况是打印显示allopt中的项目,一个元组,没有任何格式。其次,回车符chr(13)不是换行符,而是 Windows 中换行符的一部分。在 Windows 中,默认换行符是字符rn但我将使用n作为示例。

最简单的解决方案是告诉print将元组视为一系列参数,而不是单个元组参数。

In [1]: x = 5, chr(10), 6
In [2]: print(x)
(5, 'n', 6)
In [3]: print(*x)
5
6

您可以使用*variable表示法执行此操作。请注意,ASCII 字符 10n
否则,应以您认为合适的方式设置字符串的格式。也许将该逻辑包装为返回准备打印的字符串的方法。

祝你好运!

对问题的回答也是对以下内容的正确回答:

如何在 Python 中连接字符串?

我已经简化了你的例子:

def foo(self, seed, prompt, opt1, opt2, opt3, opt4):
x = prompt, chr(13), "A)", opt1, "B)", opt2, "C)", opt3, "D)", opt4
return x
r = foo(1, "hello mars", "pluto", "strawbery", "axe", "3", "4")
print(r)

输出为:

('pluto', 'r', 'A)', 'strawbery', 'B)', 'axe', 'C)', '3', 'D)', '4')

这是因为prompt, chr(13), [...]返回元,而不是字符串。 您没有将小字符串合并为一个大字符串。
相反,您创建了一个索引容器,即元组(,以便元组的每个元素都是一个字符串。

请尝试以下操作:

import io
class Dialogue:
def __init__(self, seed, prompt, opt1, opt2, opt3, opt4):
self.id = seed
self.prompt = prompt
self.opt1 = opt1
self.opt2 = opt2
self.opt3 = opt3
self.opt4 = opt4
str_strm = io.StringIO()
print(
prompt,
chr(13),
"A)", opt1,
"B)", opt2,
"C)", opt3,
"D)", opt4, sep=" ", end="n", file=str_strm)
self.allopt = str_strm.getvalue()
obj = Dialogue('strawberry', 'xxx', 'axe', 'yyyy', 'fgdff', 'fdgdfg')
print(obj.allopt)

您无需手动插入chr(13)"n"
Python 的print函数会在末尾为你加一行换行符:

str_strm = io.StringIO()
print(prompt, file=str_strm)
print("A)", opt1, file=str_strm)
print("B)", opt2, file=str_strm)
print("C)", opt3, file=str_strm)
print("D)", opt4, file=str_strm)
self.allopt = str_strm.getvalue()

连接字符串的另一种方法如下所示:

merged_string = "".join(['str1', 'str2', 'str3', 'str4', 'fgdff', 'fdgdfg'])

最新更新