How to unstring a list/tuple without eval [duplicate] - python

This question already has answers here:
Convert string to nested structures like list
(2 answers)
Closed 7 years ago.
I'm trying to use input to get the value for a tuple. However, since input sets the value as a string, I'm trying to unstring it as well. I've found that eval works for this purpose, but that it should be distrusted. While this will not be a problem as long as I use the code privately, if I were to publicly release it I want to use the best code possible.
So, is there another way of unstringing a tuple in Python 3?
Here's what I'm currently doing:
>>> a = input("What is the value? ")
What is the value? (3,4)
>>> a
'(3,4)'
>>> eval(a)
(3, 4)

Use the safe version of eval, ast.literal_eval which is designed exactly for what you are trying to achieve:
from ast import literal_eval
tup = literal_eval(a)

I'd do it like this:
>>> inp = input()
'(3,4)'
>>> tuple(map(int, inp.strip()[1:-1].split(',')))
(3, 4)
where strip will make sure leading or trailing blanks won't ruin your day.

Simple, you don't ask the user to input a tuple. Instead you do this:
x = input("Enter x value: ")
y = input("Enter y value: ")
data = (
int(x),
int(y)
)
print(
repr(data)
)
--output:--
(10, 3)

Related

How to capitalize every other character in a string [duplicate]

This question already has answers here:
Capitalise every other letter in a string in Python? [closed]
(5 answers)
Closed 3 years ago.
I want the program to return ' mahir ' as 'MaHiR', I have got MHR but how do I get 'a' and 'h' at their usual place ?
I have already tried slicing but that does not work
s = 'mahir'
a = list (s)
c = a[0:5:2]
for i in range (len(c)):
print (c[i].capitalize(),end = " ")
Python's strings are immutable, calling c[i].capitalize() will not change c[i], and therefore will not change s, to modify a string you must create a new one out of it, you can use str.join with a generator expression instead:
s = 'mahir'
s = ''.join(c.upper() if i % 2 == 0 else c for i, c in enumerate(s))
print(s)
Output:
MaHiR
If you want to do it using slicing, you could convert your string to a list since lists are mutable (but the string approach above is better):
s = 'mahir'
l = list(s)
l[::2] = map(str.upper, l[::2])
s = ''.join(l)
print(s)
Output:
MaHiR

Convert List to integer in Python [duplicate]

This question already has answers here:
Convert list of ints to one number?
(19 answers)
Closed 4 years ago.
In Python, I want to convert list into int.
so if i have input like this:
a=[1,2,3,4]
i want this output:
1234
so How it is possible?
You can use the join function in conjunction with a generator, like this:
a=[1,2,3,4]
int(''.join(str(i) for i in a))
Output:
1234
With recursion:
a=[1,2,3,4]
def f(l):
if not l: return 0
return l[-1] + f(l[:-1]) * 10
print(f(a))
This outputs:
1234
You can use generator comprehension in the following way:
result = int(''.join((str(i) for i in a)))
This turns every item of the list to a string, joins the list together and then turns the whole thing back to an integer

finding a float form a string without regex python [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I am trying to take an input from a "raw_input" function and make it into 3 floats and then sum them up.
user_input = "1.23+2.25+3.25"
is it possible to take the 3 numbers and add them to a list of floats that look like this or something similar?
float_lst = [1.23,2.25,3.25]
Yes.
float_lst = [float(i) for i in user_input.split("+")]
If I only go by your requirement, not the list, you can eval. Trivial code example below
a = raw_input()
print eval(a)
You can use the split function and then cast the elements to float.
user_input = "1.23+2.25+3.25"
lst = user_input.split("+")
lst = [float(i) for i in lst]
Now you have a list of float so you can do
result = sum(lst)
And you will have the result

How to return a string from an array [duplicate]

This question already has answers here:
How can I convert each item in the list to string, for the purpose of joining them? [duplicate]
(9 answers)
Closed 7 years ago.
keyword = raw_input ("Enter your keyword") *10000
keyword = keyword.lower()
keywordoutput = []
for character in keyword:
number = ord(character)
keywordoutput.append(number)
input1 = raw_input('Write Text: ')
input1 = input1.lower()
output1 = []
for character in input1:
number = ord(character)
output1.append(number)
output2 = [x + y for x, y in zip(output1, keywordoutput)]
print output2
That is my code so far. I am trying to create a program that uses a simple Vigenere Cypher to encrypt an inputted text. The code works perfectly, yet I am having an issue implimenting new code to return a string of 'output2'.
I get 'output2' easily, but from there i need to make it a simple string.
Eg: [1, 2, 3, 4]
becomes (1234)
I have tried, but I cant seem to implement such a thing into my code.
First you have to convert numbers into text.
output2 = map(str, output2)
Then you can use join to concatenate elements.
print "".join(output2)
Or in one line:
print "".join(map(str, output2))
try this
print ''.join(str(i) for i in output2)
One step use -> join:
output2 = ''.join([str(x + y) for x, y in zip(output1, keywordoutput)])
Check: https://docs.python.org/2/library/string.html#string.join
As the function is expecting a string type you must covert the numeric result x + y.

Create variables dynamically inside 'for' loop

I'm new to python and trying to take some coding challenges to improve my skills. I've to take input in following ways:
2
3 1
4 3
First, I get number of test cases.(2 here) Then based on that, I've to get given number of test cases that are each 2 integers. 1st is the range and second is the number to be searched in the range.
What's the correct, pythonic way of getting the input. I was thinking like this but it's obviously incorrect
num_testcases = int(raw_input())
for i in num_testcases:
range_limit = int(raw_input())
num_to_find = int(raw_input())
raw_input() is going to be read one line at a time from STDIN, so inside the loop you need to use str.split() to get the value of range_limit and num_to_find. Secondly you cannot iterate over an integer(num_testcases), so you need to use xrange()(Python 2) or range()(Python 3) there:
num_testcases = int(raw_input())
for i in xrange(num_testcases): #considering we are using Python 2
range_limit, num_to_find = map(int, raw_input().split())
#do something with the first input here
Demo:
>>> line = '3 1'
>>> line.split()
['3', '1']
>>> map(int, line.split())
[3, 1]
Note that in Python 3 you'll have to use input() instead of raw_input() and range() instead of xrange(). range() will work in both Python 2 and 3, but it returns a list in Python 2, so it is recommended to use xrange().
Use for i in range(num_testcases): instead of for i in num_testcases. Have a look at range (or xrange in Python 2). range(a) produces an iterable from 0 to a - 1, so your code gets called the desired number of times.
Also, input and raw_input take input on encountering a newline, meaning that in range_limit = int(raw_input()), raw_input returns "3 1", which you can't just convert to int. Instead, you want to split the string using string.split and then convert the individual items:
num_testcases = int(raw_input())
for i in range(num_testcases):
range_limit, num_to_find = [int(x) for x in raw_input().split()]

Categories

Resources