【问题标题】:How to join variables from two python.py [closed]如何连接来自两个 python.py 的变量 [关闭]
【发布时间】:2020-05-11 21:35:07
【问题描述】:

这很难用语言解释,但这里有一个截图 基本上我需要 addy.py 来生成州缩写,而 states.py 包含州或省全名的所有列表,所以在 addy.py 中,缩写是通过 ab = fake.province_abbr() 获得的,现在我想要它通过执行此省 = (states.ab) 从 states.py 获取省全名,但我不知道您应该如何在 states.py 上使用 ab 以使其使用或找到 addy.py 设置的缩写 States addy

【问题讨论】:

标签: python python-3.x list selenium faker


【解决方案1】:

听起来您正试图从字符串“AB”访问处于状态的变量(即变量 AB)。 This answer 在这种情况下应该可以解决问题。

# states.py
AB = ('Alberta')
BC = ('British Columbia')
# etc.
# addy.py
import states

abbr = 'AB' # get from "Faker" or wherever else
print(getattr(states, abbr))

这会打印“阿尔伯塔”

【讨论】:

  • Traceback(最近一次调用最后):文件“C:/Users/WD/PycharmProjects/paypal/start.py”,第 1 行,在 中导入 addy 文件“C:\Users\ WD\PycharmProjects\paypal\addy.py",第 19 行,在 中 print(getattr(states, ab)) AttributeError: module 'states' has no attribute 'YT' Process finished with exit code 1
  • import states import random import string from faker import Faker from random import randrange fake = Faker('en_CA') eno = randrange(0, 10) ab = fake.province_abbr() street = fake.street_address () post1 = fake.postalcode_in_province(province_abbr= ab) city = fake.city() pn = fake.phone_number() fname = fake.first_name() sname = fake.last_name() email = fname + sname + '@mail. com' print(getattr(states, ab)) print (email) name = random.choice(open('name.txt').readlines()) 这是我的新代码
  • 您的 states.py 并不包含所有地区,states.py 中缺少“YT”(育空地区)。您还缺少努纳武特 ('NU')、西北地区 ('NT') 和爱德华王子岛 ('PEI')。添加这些,我相信应该可以解决您的问题。
  • 是的,我在 5 分钟前才注意到它可以正常工作,感谢您的回答
猜你喜欢
  • 1970-01-01
  • 2012-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多