The Python way to map
printf("Enter two numbers here: ");
scanf("%d %d", &var1, &var2)
would be
var1, var2 = raw_input("Enter two numbers here: ").split()
Note that we don't have to explicitly specify split(' ') because split() uses any whitespace characters as delimiter as default. That means if we simply called split() then the user could have separated the numbers using tabs, if he really wanted, and also spaces.,
Python has dynamic typing so there is no need to specify %d. However, if you ran the above then var1 and var2 would be both Strings. You can convert them to int using another line
var1, var2 = [int(var1), int(var2)]
Or you could use list comprehension
var1, var2 = [int(x) for x in [var1, var2]]
To sum it up, you could have done the whole thing with this one-liner:
# Python 3
var1, var2 = [int(x) for x in input("Enter two numbers here: ").split()]
# Python 2
var1, var2 = [int(x) for x in raw_input("Enter two numbers here: ").split()]
Answer from kizzx2 on Stack OverflowThe Python way to map
printf("Enter two numbers here: ");
scanf("%d %d", &var1, &var2)
would be
var1, var2 = raw_input("Enter two numbers here: ").split()
Note that we don't have to explicitly specify split(' ') because split() uses any whitespace characters as delimiter as default. That means if we simply called split() then the user could have separated the numbers using tabs, if he really wanted, and also spaces.,
Python has dynamic typing so there is no need to specify %d. However, if you ran the above then var1 and var2 would be both Strings. You can convert them to int using another line
var1, var2 = [int(var1), int(var2)]
Or you could use list comprehension
var1, var2 = [int(x) for x in [var1, var2]]
To sum it up, you could have done the whole thing with this one-liner:
# Python 3
var1, var2 = [int(x) for x in input("Enter two numbers here: ").split()]
# Python 2
var1, var2 = [int(x) for x in raw_input("Enter two numbers here: ").split()]
You can't really do it the C way (I think) but a pythonic way of doing this would be (if your 'inputs' have spaces in between them):
raw_answer = raw_input()
answers = raw_answer.split(' ') # list of 'answers'
So you could rewrite your try to:
var1, var2 = raw_input("enter two numbers:").split(' ')
Note that this it somewhat less flexible than using the 'first' solution (for example if you add a space at the end this will already break).
Also be aware that var1 and var2 will still be strings with this method when not cast to int.
Split string into different variables instead of array in Python - Stack Overflow
python - Split User input into different Variables - Stack Overflow
python - How to split a variable into two different variables? - Stack Overflow
Split a string into multiple int variables
SOLVED: Can someone share a more pythonic method for splitting a space separated input, assigning the values to two different variables and changing one of the variable types to an integer and storing them in an OrderedDict, and collecting up the total number of items.
For example, you're given a number telling you how many sequences will follow, then a sequence strings, each with a fruit names (some with spaces) and the number of pieces of that fruit:
7 kiwi fruit 5 bananas 2 oranges 3 apples 2 jack fruit 3 kiwi fruit 2 apples 5
The method I've used so far uses OrderedDict and Counter to make an OrderedCounter (thanks Raymond Hettinger!), but I think my use of regular expressions here is a but janky. Any better/cleaner ways of doing this?
from collections import OrderedDict, Counter
import re
class OrderedCounter(Counter, OrderedDict):
pass
if __name__ == '__main__':
items_counts = OrderedCounter()
for i in range(int(input())):
name_count = re.split(r"\s(?=\d)", input())
items_counts[name_count[0]] += int(name_count[1])
for key in items_counts:
print(f'{key} {items_counts[key]}')_______________________________________________________________________________________________________
EDIT - new solution
Thanks to u/commandlineluser I've simplified this to:
from collections import OrderedDict
if __name__ == '__main__':
items_prices = OrderedDict()
for i in range(int(input())):
name, price = input().rsplit(" ", 1)
try:
items_prices[name] += int(price)
except:
items_prices[name] = int(price)
for key, val in items_prices.items():
print(f'{key} {val}')
You could do:
a, b, c, d = input().split(".")
The split() method, by default, splits a string at each space into a list. But, if you add the optional argument, it will split a string by that character/string. You can read more about it at the official documentation
You can also check to make sure the input is in proper IPv4 format.
if re.match("\d+[.]\d+[.]\d+[.]\d+", input()):
print("IPv4 format")
might want to add the following to filter for a valid IP:
while(1):
IP=raw_input("Enter an IP Address:")
if re.search("\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}",IP):
break
else:
print"Invalid Format!"
variable1, variable2, variable3, variable4 = IP.split(".")
verb, _, params = move.partition(" ")
verbwill be first word_will be the separator, whitespace in this caseparamswill be the rest after the verb
First you want to get the input:
varName = raw_input("Enter anything: ")
Then you want to split the input
splitted_results = varName.split()
print splitted_results
This will give you a list of strings split by empty space. You can loop through as so:
for sr in splitted_results:
print sr
Howdy!
I have a table with some input parameters. A group of those parameters are (x,y) coordinates written in a single cell on excel as (x,y). The value is considered as a string "(x,y)", but I need to extract the values and put them into an Int variable.
#click1="[100,200]"
click1=click1.strip('][').split(',')
x1,y1=click1
The issue is that I have 5 Click variables (Click1, Click2, etc...), and the final variable x1, y1, etc... are type string and not int. So for each operation (turn string into list, assign value to x1 y1, change value/type to int) I'd be using 5 rows, one for each Click variables.
How can I do this in a smart way?
Cheers!
If you're sometimes unsure about how many lines there are, you'd be forced to dynamically create variable names. Don't do this. This is almost always the wrong approach to take, and a better way exists.
Instead, use the list that .split() produces directly, and process the data inside of that.
If you need to further split each line in your string into two parts, you can use nested lists. Here is a simple example of the method I think you should use instead:
# your input string
string = "first line\nsecond line\nthird line\nfourth line"
# use a list to store your data, and proccses it instead.
data = []
for line in string.split('\n'):
# split each line into two parts.
first_part, second_part = line[:-4], line[-4:]
data.append([first_part, second_part])
# data:
#
# [['first ', 'line'],
# ['second ', 'line'],
# ['third ', 'line'],
# ['fourth ', 'line']]
print(data)
You can access each part of data using a certain index. For example, if you wanted to process the first line of string, you could use data[0] which yields ['first ', 'line'].
something like below
>>> a="""this is a
multiline
string"""
>>> for eachline in a.split('\n'): print(eachline)
this is a
multiline
string
You're calling the function wrongly.
>>> "hello world".split()
['hello', 'world']
split slits a string by a space by default, but you can change this behavior:
>>> "hello, world".split(',')
['hello', ' world']
In your case:
a,b= input("Please enter two digits separated by space").split()
The str.split() function is an attribute of the type str (string). To call it, you do:
input("Please enter two digits separated by space").split()
Note that .split(" ") isn't needed as that is what it is by default.
You can assign to different variables. Like in Perl, you just need to define them in an array, so assignation is done by matching position of variable and result.
Here is something I tried in interactive python:
>>> # this is a grep result, btw
... foo = 'config/some.conf:12: title = "Super Me"'
>>> [ filename, line, text ] = foo.split(':')
>>> print text
title = "Super Me"
I do like this rather than a dictionary or an array, especially when working in a for loop. It makes variable names more meaningful, even if local to the loop, or temporary.
Edit
second edit to integrate codeforester's notes (Thanks).
To avoid searching for variables usage, unwanted values can be dummied to clearly state it will not be used.
Dummy variables are expected as _ by python linter
>>> [ _, line, text ] = foo.split(':')
If you don't need the List properties with your variables, you can just remove the square brackets (variables are then managed as a tuple):
>>> filename, line, text = foo.split(':')
If you are not sure about the tokens quantity, use the extended iterable, which requires a List:
>>> [ filename, line, text, *_ ] = foo.split(':')
End of edit
Readability for the win !
lst = foo.split("|")
lst[0]
lst[1]
...