How to remove \n at the end of each value? - python

I want to make the input such that the user will type a separate number on each new line. I managed to put together this code
def str2arr(str):
arr = []
for line in str:
arr.append(str.replace('\n', ''))
return arr
import sys
a = sys.stdin.readlines()
print(a)
It is working nearly as I would like to, but the output looks like
['6543\n', '6543\n', '7654\n']
Is there a clever way to remove the \n?
And also, will I even get an usable integers using this method?
Thank you guys in advance.

You could use
a = ['6543\n', '6543\n', '7654\n']
integers = list(map(int, a))
print(integers)
# [6543, 6543, 7654]

Have a look at string.strip. That should provide the expected result.
You'll then have to call int() on each of the entries in the list.
Example:
>>> t = ['6543\n', '6543\n', '7654\n']
>>> [int(x.strip()) for x in t]
[6543, 6543, 7654]

Related

get attribute containing a certain string of a named tuple python

is it possible to get the first argument that contain a certain string in a named tuple such has:
import collections
data_line = collections.namedtuple('ex', 'a_1 b_1 a_2')
data = data_line(a_1=10, b_1=11, a_2=10)
getattr(data, 'a_2')
I would like to get the first argument that contain the string 'a', something like:
getattr(data, contains('a'))
any pythonic way to acheive this? thanks!
You can get it done by accessing the fields of the namedtuple and slicing the output to get your desired result:
Either:
[getattr(data, x) for x in data._fields if x.startswith('a')][0]
Or:
getattr(data, [x for x in data._fields if x.startswith('a')][0])
I hope this helps.
Maybe this is not what you want exactly but you can try something like this:
def contains(val):
if val.startswith('a'):
return True
else:
return False
for a in filter(contains, data._fields):
getattr(data, a)
and you may want to have a list of a's:
a_list = list(filter(contains, data._fields))

Function Definition: Matching Area Codes to Phone Numbers

If I want to define a function called match_numbers, which would match the area code from one list to the phone number of another list, how should I fix my code? For example:
match_phone(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
would give me
(666)313-2534
(332)123-3332
My code is:
def phone (nlist, nlist1):
results = {}
for x in nlist1:
results.setdefault(x[0:3], [])
results[x[0:3]].append(x)
for x in nlist:
if x in results:
print(results[x])
The problem with this code is, however:
It gives me the outputs in brackets, whereas I want it to print
the output line by line like shown above, and
it won't work with the parantheses in the 2nd list (for example
(666)543-2322 must be converted as 666-543-2322 for the list to
work.
Now, there are better/faster approaches to do what you are trying to do, but let us focus on fixing your code.
The first issue you have is how you are slicing your string. Remember that you start at index 0. So if you do:
x[0:3]
What you are actually getting is something like this from your string:
(12
Instead of your intended:
123
So, knowing that indexes start at 0, what you actually want to do is slice your string as such:
x[1:4]
Finally, your line here:
results[x[0:3]].append(x)
There are two problems here.
First, as mentioned above, you are still trying to slice the wrong parts of your string, so fix that.
Second, since you are trying to make a key value pair, what that above line is actually doing is making a key value pair where the value is a list. I don't think you want to do that. You want to do something like:
{'123': '(123)5556666'}
So, you don't want to use the append in this case. What you want to do is assign the string directly as the value for that key. You can do that as such:
results[x[1:4]] = x
Finally, another problem that was noticed, is in what you are doing here:
results.setdefault(x[1:4], [])
Based on the above explanation on how you want to store a string as your value in your dictionary instead of a list, so you don't need to be doing this. Therefore, you should simply be removing that line, it does not serve any purpose for what you are trying to do. You have already initialized your dictionary as results = {}
When you put it all together, your code will look like this:
def match_phone(nlist, nlist1):
results = {}
for x in nlist1:
results[x[1:4]] = x
for x in nlist:
if x in results:
print(results[x])
match_phone(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
And will provide the following output:
(666)313-2534
(332)123-3332
If all the phone numbers will be in the format (ddd)ddd-dddd you can use
for number in (num for num in nlist1 if num[1:4] in nlist):
print(number)
You could use some better variable names than nlist and nlist1, in my view.
def match_phone(area_codes, numbers):
area_codes = set(area_codes)
for num in numbers:
if num in area_codes:
print num
You could do something like this:
phone_numbers = ['(443)241-1254', '(666)313-2534', '(332)123-3332']
area_codes = ['666', '332']
numbers = filter(lambda number: number[1:4] in area_codes, phone_numbers)
for number in numbers:
print(number)
Another similar way to do this without using a filter could be something like this:
for number in phone_numbers:
if number[1:4] in area_codes:
print(number)
Output in either case would be:
(666)313-2534
(332)123-3332
No one with regex solution! This may be an option too.
import re
def my_formatter(l1,l2):
mydic = {re.match(r'([(])([0-9]+)([)])([0-9]+[-][0-9]+)',i).group(2):re.match(r'([(])([0-9]+)([)])([0-9]+[-][0-9]+)',i).group(4) for i in l2}
for i in l1:
print "({0}){1}".format(str(i),str(mydic.get(i)))
my_formatter(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
It prints-
(666)313-2534
(332)123-3332

How do I take my random string and assign it to a variable?

So essentially I have this printing strings from my three lists...and I want to store what's produced into another list. I know how to store to other list but I can't figure a way to capture what is produced.
print(random.choice(a), random.choice(b), random.choice(c))
Is there a way to assign/record what is produced as a result of this statement?
Sorry if this is really easy or something...i'm just barely starting out.
You can use str.format:
In[3]: import random
In[4]: import string
In[5]: var = "{} {} {}".format(random.choice(string.ascii_lowercase), random.choice(string.ascii_lowercase), random.choice(string.ascii_lowercase))
In[6]: print(var)
z j j
You can join them too. Change ' ' to what you want the delimiter to be.
string = ' '.join(random.choice(a), random.choice(b), random.choice(c))

Python Lists -Syntax for '['

I need to declare certain values in List.
Values looks like this:
["compute","controller"], ["compute"] ,["controller"]
I know the List syntax in python is
example = []
I am not sure how I will include square brackets and double quotes in the List.
Could anyone please help.
I tried the following:
cls.node = ["\["compute"\]","\["controller"\]"]
cls.node = ["[\"compute\"]","[\"controller\"]"]
Both did not work.
I think you mean list not dictionary because that is the syntax of a list:
You can simply do it using the following format '"Hello"':
cls.node = ['["compute"]','["controller"]']
cls.node = ['["compute"]','["controller"]']
Demo:
s = ['["hello"]', '["world"]']
for i in s:
print i
[OUTPUT]
["hello"]
["world"]

Reversing string in python using def

Can anyone help me with the assignment - I have to reverse a string by using def. I am not allowed to use approaches like [::-1] or .reversed...
The following function works, but prints vertically:
def ex1(name):
for x in range(len(name)-1,-1,-1):
print(name[x])
k
r
o
Y
w
e
N
how do I put the letters back into horizontal order?? Anyone? Thanks!
You can use str.join and a list comprehension like so:
>>> def ex1(name):
... return "".join([name[x] for x in range(len(name)-1,-1,-1)])
...
>>> print(ex1('abcd'))
dcba
>>>
Also, notice that I made the function return the string instead of print it. If your teachers want you to use def for this job, then they probably want that too. If not, then you can always replace return with print if you want.
You were very close:
def ex1(name):
reverseName=""
for x in range(len(name)-1,-1,-1):
reverseName+=name[x]
print reverseName
The print statement prints a newline character (a line break) after each line, this is why you get your characters in vertical. The solution is not to print the character in each loop, but to collect them in a string and print the final string at once at the end.
Note that there are more efficient ways of doing this (see the other answers), but it might be the most straightforward way and the closest one to what you have already done.
Here is another way that you can reverse a string.
def ex1(name):
length = len(name)
return "".join([name[length-x-1] for x in range(0, length)])
print ex1("hello world")
name=input("Whats your name ?")
def reversemyname(name):
x=name[::-1]
return x
reversedname=reversemyname(name)
print(reversedname)
print(name[x]), # <= add that comma
if you want the output like this kroy wen then try this:
sys.stdout.write(name[x])
remember to import sys

Categories