[英]How do I print a string based on the length given as input?
What I want to achieve is:我想要实现的是:
Suppose the length that the user inputs is 6. Then the string that is to be input should also be of length 6 (without having any whitespaces in between the characters) .假设用户输入的长度是 6。那么要输入的字符串的长度也应该是 6 (字符之间没有任何空格) 。
My code:我的代码:
length=int(input())
S=input().split(" ",length) # This works, but I have to provide spaces in between.
My expected input should be like:我的预期输入应该是:
>>>6
abcdef
If I run the code above, then the input is like:如果我运行上面的代码,那么输入是这样的:
>>>6
a b c d e f
Alternative 1:备选方案 1:
If the string needs to be user input, the following might work:如果字符串需要用户输入,以下可能会起作用:
length=int(input())
S=input()[:length]
print(S)
Alternative 2:备选方案 2:
Assuming the string generated needs to be random, One way of doing this is by using two modules namely:假设生成的字符串需要是随机的,一种方法是使用两个模块,即:
Code Looks as follows:代码如下所示:
import random
import string
#Function to generate string
def get_random_string(length):
letters = string.ascii_lowercase
result_str = ''.join(random.choice(letters) for i in range(length))
print("Random string of length", length, "is:", result_str)
#Calling the function to generate string of desired range:
get_random_string(6)
The Output then is as follows: Output 则如下:
a = input("What is your name?") Print(len(a)) a = input("你叫什么名字?") Print(len(a))
Or print(len(input("What is your name?")))或 print(len(input("你叫什么名字?")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.