How do I print a string based on the length given as input?
Question:
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).
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
Answers:
Alternative 1:
If the string needs to be user input, the following might work:
length=int(input())
S=input()[:length]
print(S)
Alternative 2:
Assuming the string generated needs to be random, One way of doing this is by using two modules namely:
- random
- string
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:
a = input("What is your name?")
Print(len(a))
Or
print(len(input("What is your name?")))
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).
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:
If the string needs to be user input, the following might work:
length=int(input())
S=input()[:length]
print(S)
Alternative 2:
Assuming the string generated needs to be random, One way of doing this is by using two modules namely:
- random
- string
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:
a = input("What is your name?")
Print(len(a))
Or
print(len(input("What is your name?")))