计算变量python中的字符

时间:2016-09-14 11:58:35

标签: python variables

我正在尝试创建一个程序来打印一行文本一定次数,我想限制第一个文本条目中的字母数量,我无法弄清楚如何。

代码:

# Hello World Script 2.0

import random
**------------------------------------------------
#i want to limit the amount of characters, how?
------------------------------------------------**
print("What do you want to be printed?(Max 20 Characters)")
var0 = input("> ")

print("Please enter the amount of times you want that printed(max 100000)")
print('Or enter "R" for a random number')
var2 = input("> ")

if int(var2) > 100000:
    print("That number is too high, please restart the proram and enter something smaller.")
    exit()

if var2 == "r":
    var2 = random.randint(1,100000)


var1 = var0 * int(var2)
print(var1, var2)

1 个答案:

答案 0 :(得分:0)

您可以使用函数len()检查字符串的长度。

import random
**------------------------------------------------
#i want to limit the amount of characters, how?
------------------------------------------------**
print("What do you want to be printed?(Max 20 Characters)")
var0 = input("> ")

if len(var0) > 20:
   print("That is too long")
   exit()

print("Please enter the amount of times you want that printed(max 100000)")
print('Or enter "R" for a random number')
var2 = input("> ")

if int(var2) > 100000:
    print("That number is too high, please restart the proram and enter something smaller.")
    exit()

if var2 == "r":
    var2 = random.randint(1,100000)


var1 = var0 * int(var2)
print(var1, var2)