【问题标题】:Printing line between variables, how do I stop this? [duplicate]变量之间的打印线,我该如何停止? [复制]
【发布时间】:2020-01-17 08:09:13
【问题描述】:

Python 代码在名字、姓氏和电子邮件地址之间输出一个新行,我怎样才能阻止这种情况发生?例如

ogchu
@gmail.com
ogchu
@yahoo.com
ogchu
@hotmail.com
ogchu
@aol.com
ogchu
@bigpond.com

first.txt 和 last.txt 文件分别有大约 2,000 个和 100 个名称,因此手动浏览并做一些事情并不是一个真正的选择。

代码的目的是尝试生成看起来真实的电子邮件地址,有时包含名字和姓氏,有时包含 1 个首字母和一个姓氏,有时包含 2 个首字母和一个姓氏。

代码:

import random
import string
import time

count = 0
while count < 50:
    x = random.randint(0, 1)
    y = random.randint(0, 1)
    z = random.randint(0, 1)
    if x == 0:
        prefix1 = random.choice(string.ascii_lowercase)
        prefix2 = random.choice(string.ascii_lowercase)
        first = ""
    if x == 1:
        prefix1 = random.choice(string.ascii_lowercase)
        prefix2 = ""
        first = ""
    if x == 1 and y == 1:
        prefix1 = ""
        prefix2 = ""
        first = random.choice(open('first.txt').readlines())

    last = random.choice(open('last.txt').readlines())

    print(prefix1 + prefix2 + first + last + "@gmail.com")
    print(prefix1 + prefix2 + first + last + "@yahoo.com")
    print(prefix1 + prefix2 + first + last + "@hotmail.com")
    print(prefix1 + prefix2 + first + last + "@aol.com")
    print(prefix1 + prefix2 + first + last + "@bigpond.com")
    print(prefix1 + prefix2 + first + last + "@icloud.com")
    print(prefix1 + prefix2 + first + last + "@outlook.com")
    count = count + 1
    time.sleep(3)

【问题讨论】:

  • ... + last.strip() + ...?您正在从文件中读取这些名称,这些行后面有换行符。
  • @jonrsharpe 所以我需要从两个文件的每一行中删除换行符吗?我可以写一个程序来帮我做吗?
  • @jonrsharpe:我已经重新打开了它(甚至在阅读您的评论之前:-))
  • 如果您从文件中删除了换行符,这有什么帮助?是的,可以编写一个程序来做到这一点,但是你会读到一行,所有的名字都混在一起了。只需按照我上面的建议进行操作,使用 strip 方法从所选值中删除换行符。

标签: python variables printing


【解决方案1】:

问题出在

first = random.choice(open('first.txt').readlines())

last = random.choice(open('last.txt').readlines())

读取一行时,最后一个字符是\n(换行符)。您需要通过调用.strip() 方法将其删除,例如:

last = last.strip()
first= first.strip()

【讨论】:

  • 谢谢!一切都解决了,我很惊讶你们帮助的速度(第一次使用堆栈)就像 2 分钟一样。
猜你喜欢
  • 1970-01-01
  • 2016-03-22
  • 2021-12-29
  • 1970-01-01
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多