Как ввести несколько переменных в строку python
Перейти к содержимому

Как ввести несколько переменных в строку python

  • автор:

4 ways to add variables or values into Python strings

Bisola Olasehinde

Sometimes, there’s a need to include a variable or non-string datatypes into a string literal.

1. The comma

The most common way is to separate strings and variables with a comma as shown below.

This does not give a lot of ability to customize the output and still have everything look good. We also need to take note that each comma separation is a `space` in the output string.

We can do better.

2. The % operator

This is an old school method but you’ll still see it quite frequently. In fact, I use it a lot too.

This gives us more flexibility but there are 2 major limitations.

1. You can’t include any datatype such as list, datetime etc

2. %s is for string, %d for int and %f for float. You must not mistake one for another.

With the example above, there’s no error because the datatypes were convertible.

Therefore, python automatically cast the necessary datatype unto the input.

However, there are some floats e.g `infinity` that can’t be converted to int.

When there are more than one arguments for the % operator, it has to be a tuple. And lastly, you can specify the length of a float as shown below (dot followed by the number of decimal places).

3. The string format method

Python string has a format method which let’s you insert any datatype. It is very similar to % operator (with `%s` or `%d` or `%f` replaced with `<>`), but better.

The format method is better because

1. You don’t have to be sure about the datatype.

2. You can insert any datatype.

3. You can repeatedly use a value by indexing.

The last index example also illustrates that the values in the format method can be expressed as a list of key=value pairs.

4. f strings

Another attractive option is the formatted string literal (f-string).

The main advantage is that it lets you readily know where a value is, and I just think it looks �� ��. But the downsides are

1. It requires python>=3.6. You have to be certain of that to avoid an error.

2. You can’t include a backslash in the expression part (inside `<>`).

3. Point 2 also means that you can’t include `”` without getting a SyntaxError.

Ввод нескольких переменных в одной строке

Ввод нескольких переменных в одной строке
Всем здравствуйте. Не давно начал изучать питон и решил порешать задачи. И буквально на первой.

Инициализация нескольких переменных в одной строке
Привет. Иногда нужно инициализировать переменные, иначе программа не запускается. Я сейчас так.

Ввод нескольких значений в одной строке
#include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; int main() < int count; cin &gt;&gt;.

Как можно сделать ввод 3 переменных в одной строке?
Как можно сделать ввод 3 переменных в одной строке, чтобы программа была компактней? using.

Написать программу, которая обеспечивает ввод значений дробных переменных (типа float) u и r. Предполагается, что пользователь будет набирать числа в одной строке.
Немного непонятная задачка. Тут пользователь может вводить данные &quot;значение пробел значение&quot;.

Read two variables in a single line with Python [duplicate]

I am familiar with the input() function, to read a single variable from user input. Is there a similar easy way to read two variables?

I’m looking for the equivalent of:

One way I am able to achieve this is to use raw_input() and then split what was entered. Is there a more elegant way?

This is not for live use. Just for learning..

9 Answers 9

No, the usual way is raw_input().split()

In your case you might use map(int, raw_input().split()) if you want them to be integers rather than strings

Don’t use input() for that. Consider what happens if the user enters

John La Rooy's user avatar

You can also read from sys.stdin

I am new at this stuff as well. Did a bit of research from the python.org website and a bit of hacking to get this to work. The raw_input function is back again, changed from input. This is what I came up with:

Granted, the code is not as elegant as the one-liners using C’s scanf or C++’s cin. The Python code looks closer to Java (which employs an entirely different mechanism from C, C++ or Python) such that each variable needs to be dealt with separately.

In Python, the raw_input function gets characters off the console and concatenates them into a single str as its output. When just one variable is found on the left-hand-side of the assignment operator, the split function breaks this str into a list of str values .

In our case, one where we expect two variables, we can get values into them using a comma-separated list for their identifiers. str values then get assigned into the variables listed. If we want to do arithmetic with these values, we need to convert them into the numeric int (or float) data type using Python’s built-in int or float function.

I know this posting is a reply to a very old posting and probably the knowledge has been out there as "common knowledge" for some time. However, I would have appreciated a posting such as this one rather than my having to spend a few hours of searching and hacking until I came up with what I felt was the most elegant solution that can be presented in a CS1 classroom.

Python: Как считать два числа через пробел

Python — это один из самых популярных языков программирования на сегодняшний день. Он прост в изучении, имеет понятный и согласованный синтаксис. Одной из часто встречающихся задач является считывание двух чисел через пробел. В этой статье мы рассмотрим, как это делается.

Использование функции input() и split()

Чтобы считать два числа через пробел, мы можем использовать функцию input() , которая используется для считывания данных, введенных пользователем, и функцию split() , которая разделяет строку на список подстрок.

В этом коде мы используем input() для получения строки ввода, split() для разделения строки на две подстроки по пробелу, а затем функцию map() для преобразования этих подстрок в числа.

Обработка ошибок

Важно также учесть, что пользователь может ввести не то, что мы ожидаем. В таком случае, следует использовать конструкцию try/except для обработки возможных ошибок.

В данном случае, если пользователь введет что-то, что нельзя преобразовать в число, или введет больше или меньше двух значений, то код выведет сообщение об ошибке.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *