[英]How to print a tick/checkmark character on the same line as the string in python
所以我有一個字符串,我正在從文件中讀取。 如果我的程序滿足某個條件,我想在它旁邊打印一個勾號。 如果打印在字符串的下一行,打勾怎么辦。 這是負責打印字符串的函數。
def printData(self):
spaces = " " * self.getLevel() * 4 + "|__" if self.getLevel() != 0 else ""
if self.completed:
print(spaces + self.data + u'\u2713')
else:
print(spaces + self.data)
for child in self.children:
print(child.printData())
return ""
上面代碼中,self.data其實就是要打印的字符串。 我知道為什么會發生這種情況,但不知道如何解決。 當我打印出包含字符串的列表時,它在每個字符串的末尾附加了換行符,這可能會迫使刻度線移動到下一行。 這是我如何讀取文件中的數據。
def getCompData(self):
with open("subdata.txt", "r") as f:
lines = f.readlines()
for line in lines:
if line[0] == "c":
self.compTopics.append(line[1:])
return self.compTopics
我嘗試使用end=""
如下,但它也不起作用。
if self.completed:
print(spaces + self.data, end="")
print(u'\u2713')
任何有關如何解決此問題的想法將不勝感激。 謝謝
您的問題似乎在此功能中。 readlines()
函數在末尾保留\\n
字符。 要解決該問題,請使用line.rstrip('\\n')
。 這應該是您修改后的功能:
def getCompData(self):
with open("subdata.txt", "r") as f:
lines = f.readlines()
for line in lines:
if line[0] == "c":
self.compTopics.append(line.rstrip('\n')[1:])
return self.compTopics
這部分現在按預期工作:
if self.completed:
print(spaces + self.data, end="")
print(u'\u2713')
希望您的功能現在按預期工作:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.