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
Asked By: user14373544

||

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:

Output

Answered By: aryashah2k

a = input("What is your name?")
Print(len(a))

Or
print(len(input("What is your name?")))

Answered By: nuru ayaga
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.