打印字符串,而不是字符数

2024-04-23 08:47:00 发布

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

我正在努力工作,因为我是一个全新的程序员。我还没学那么多,所以我在做基本代码。 我使用随机变量来打印变量附带的字符串,而不是字符串中的字符数。你知道吗

抱歉,如果有人生气,但我似乎找不到解决这个问题的任何地方,如果有一个我一定是输入了错误的搜索

先谢谢你。你知道吗

代码:

import random

EFile=open("ExternalFile.txt","w+")
Info1=EFile.write("Shotgun - George Ezra")
Info2=EFile.write("God's Plan - Drake")
Info3=EFile.write("This is me - Kiara Settle")
Info4=EFile.write("Solo - Clean Bandit")
Info5=EFile.write("Psyco - Post Malone")
EFile.close

Array=[Info1, Info2, Info3, Info4, Info5]


Efile=open("ExternalFile.txt","r")

RanVar=random.choice(Array)
print(RanVar)

我想让它打印字符串,也就是在括号里,但它打印的字符数量,我不明白为什么。你知道吗


Tags: 字符串代码txtrandomopen字符arraywrite
3条回答

EFile.write(string)的返回值是写入的字符数,而不是写入的内容。最好将要写入文件的所有内容都存储在一个列表中。我还假设你想用新行写每首歌的名字。另外,它不是强制性的,但是不需要将变量名大写,这违反了惯例。你知道吗

import random

songs = ["Shotgun - George Ezra", "God's Plan - Drake", "This is me - Kiara Settle", "Solo - Clean Bandit", "Psyco - Post Malone"]

efile = open("ExternalFile.txt", "w+")

for song in songs:
    efile.write(song + "\n")

efile.close()

ran_var = random.choice(songs)
print(ran_var)

这对于您的技能水平来说可能有点高级,但是使用with块处理文件是很好的:

with open("ExternalFile.txt", "w+") as efile:
    for song in songs:
        efile.write(song + "\n")

with块自动关闭文件。你知道吗

(...)
Efile=open("ExternalFile.txt","r")
lines_at = random.randrange(0, len(Array))
lines = Efile.readlines()
print(lines[lines_at])

此代码将起作用。你知道吗

import random

EFile=open("ExternalFile.txt","w+")

Info1=("Shotgun")
Info2=("God's Plan")
Info3=("This is me")
Info4=("Solo")
Info5=("Psyco")

EFile.write(Info1)
EFile.write(Info2)
EFile.write(Info3)
EFile.write(Info4)
EFile.write(Info5)
EFile.close

Array=[Info1, Info2, Info3, Info4, Info5]

RanVar=random.choice(Array)
print(RanVar)

我觉得这个代码更合适,因为我需要进一步分裂字符串和打印只是每个歌曲名称的第一个字符,因为这是一个代码猜测游戏。你知道吗

这是谢尔顿提出的,我能够理解和处理它。你知道吗

谢谢你的帮助!你知道吗

相关问题 更多 >