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

时间:2019-01-07 08:41:50

标签: python python-3.x

由于我是一名全新的编码员,所以我正在尝试工作。好吧,我还没有学到太多,所以我正在做基本代码。 我正在使用随机变量来打印变量附带的字符串,而不是字符串中的字符数。

对不起,如果有人惹恼了我,但我似乎无法在任何地方找到解决此问题的方法,如果有,我必须输入错误的搜索结果

谢谢。

代码:

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)

我希望它打印出方括号中的字符串,但是它打印出的字符数,我不明白为什么。

3 个答案:

答案 0 :(得分:2)

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块会自动关闭文件。

答案 1 :(得分:0)

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

此代码将起作用。

答案 2 :(得分:0)

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)

我觉得这段代码更合适,因为我将需要拆分字符串并仅打印每个歌曲名称的第一个字符,因为这是一个代码猜测游戏。

这是谢尔顿的建议,我能够理解和使用它。

不过,谢谢您的帮助!