Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I limit the amount of letters in a string

I have a program that asks a the user to input a question, the program then answers it. What I want to know is how do I limit the amount of letters a user can input into a variable.

like image 814
Jacob cummins Avatar asked Feb 11 '15 22:02

Jacob cummins


People also ask

How do I limit characters in a string in Java?

Append("123456789"); sbMax. Append("0"); This code creates a StringBuilder object, sbMax , which has a maximum length of 10 characters. Nine characters are appended to this string and then a tenth character is appended without a problem.

How do I limit string input?

Complete HTML/CSS Course 2022 To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.

How do I limit characters in a string in python?

Use a formatted string literal to format a string and limit its length, e.g. result = f'{my_str:5.5}' . You can use expressions in f-strings to limit the string's length to a given number of characters.

How do I limit characters in a string C++?

can i limit number of characters to 50? You can construct a string with the capacity to hold 50 characters by using: std::string str(50, '\0'); However, unlike C arrays, it is possible to increase its size by adding more data to it.


1 Answers

Python's input function cannot do this directly; but you can truncate the returned string, or repeat until the result is short enough.

# method 1
answer = input("What's up, doc? ")[:10]  # no more than 10 characters

# method 2
while True:
    answer = input("What's up, doc? ")
    if len(answer) <= 10:
        break
    else:
        print("Too much info - keep it shorter!")

If that's not what you're asking, you need to make your question more specific.

like image 176
Hugh Bothwell Avatar answered Oct 20 '22 21:10

Hugh Bothwell