.join() gives back list as a result in python - python

Could someone, please, explain why .join() behaves in the following way:
input = [1, 0, 5, 3, 4, 12, 19]
a = " ".join(str(input))
print(a)
And the result is:
[ 1 , 0 , 5 , 3 , 4 , 1 2 , 1 9 ]
Not only is there still a list, but also an additional space.
How come?
When I use map() it works:
a = " ".join(list(map(str, input)))
But I would like to know what is wrong with the .join method I'm using.

str(input) returns one string '[1, 0, 5, 3, 4, 12, 19]', so then join uses each character of the string as input (a string is an iterable, like a list), effectively adding a space between each.
The effect is more visible if we join with a -: '[-1-,- -0-,- -5-,- -3-,- -4-,- -1-2-,- -1-9-]'
In contrast, list(map(str, input)) converts each number to string, giving a list of strings (['1', '0', '5', '3', '4', '12', '19']), which join then converts to '1 0 5 3 4 12 19'

See #mozway's answer to understand .join()'s behavior.
To get what you want (using join), you should try this:
input = [1, 0, 5, 3, 4, 12, 19]
a = " ".join([str(i) for i in input])
print(a)
Output:
1 0 5 3 4 12 19

Related

split space separated numeric string into a list in Python3

Split space separated Numerical String into a List containing Numbers.
I want this:-
A = '5 2 12 4 29'
to be this in single line of code
B = [5,2,12,4,29]
You can also use the lambda function as following:
A = '5 2 12 4 29'
B = list(map(lambda x: int(x), a.split()))
print(B)
where split() returns a list of strings
and then map function iterates over each string where lambda function converts each string to Integer.
Try this
.split() method returns a list of splitted strings. So you can iterate over it and convert it to a integer
A = '5 2 12 4 29'
B = [int(l) for l in A.split()]
['5', '2', '12', '4', '29']
.split() method will return something like this. But you want them in integers. So you can follow the above method
You can use in python3 this style:
A = '5 2 12 4 29'
B = A.split(" ")
In this case, the split method, with the quotes is used to separate with spaces, as the A has number with spaces, then the quotes to separate would be split(" ")
print(B)
# ['5', '2', '12', '4', '29']
Here is a one-liner using a list comprehension:
A = '5 2 12 4 29'
B = [int(x) for x in A.split()]
print(B) # [5, 2, 12, 4, 29]
You can use split( ) to convert the string to a list of individual characters. ['5', '2', '12', '4', '29']
Since you want integers and not characters, you can use map() to convert those individual characters to integers.
A = '5 2 12 4 29'
B = list(map(int,A.split()))
print(B)
[5, 2, 12, 4, 29]

Convert string with hard coded line breaks into matrix in python

I am trying to create a class that takes a string of digits with hard coded line breaks and outputs a matrix and details about that matrix. In the first instance i just want to be able to create the matrix but I am struggling. I'm aware that I could probably do this very easily with numpy or something similar but trying to practice.
class Matrix:
def __init__(self, matrix_string):
self.convert_to_list = [int(s) for s in str.split(matrix_string) if s.isdigit()]
self.split = matrix_string.splitlines()
I think i want to combine the two things I have already done but I cant figure out how to apply my convert_to_list method to every element in my split method.
Getting very confused.
SAMPLE INPUT/OUTPUT
Input = " 1 8 7 /n 6 18 2 /n 1 9 7 "
Desired Output = [[1, 8, 7], [6, 18, 2], [1, 9, 7]]
It looks like you want a list of lists. For that you can use nested list comprehension.
s = " 1 8 7 /n 6 18 2 /n 1 9 7 "
lst = [[int(x) for x in r.split()] for r in s.split('/n')]
print(lst)
Output
[[1, 8, 7], [6, 18, 2], [1, 9, 7]]
It's not that hard actually:
s = " 1 8 7 /n 6 18 2 /n 1 9 7 "
print([i.split() for i in s.split('/n')])
easier way but longer:
s = s.split('/n')
new = []
for i in s:
new.append(i.split())
print(new)
output:
[['1', '8', '7'], ['6', '18', '2'], ['1', '9', '7']]

Assigning numbers to given string's letters

I am currently trying to finish a project which wants encode given paragraph using given matrix. I wanted to start make a letter list:
letterlist = np.array([" ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"])
letterlist2 = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
samplestr = "MEET ME MONDAY"
My goal is convert the letters to integer in order like A=1,B=2...Z=26 and " "=0. Then assign them to 1x3 arrays. like
But I couldn't even make a progress. First I tried make for loops to match same letter in the letter list and samplestr. Then if they are same, give the order in the letterlist as integer. But I didn't get any output.
for letter in samplestr:
for letter2 in letterlist:
if letter2==letter:
print("x") ## To see if I get any match
I don't know where did I wrong and how should I continue this. Would making dictionary make it easier to assign letters to integers? Need some advices. Thanks for your time.
The conversion to a number is done by converting the char to a ordinary number and then subtracting 64 because that is the starting ASCII-Index for 'A'
Code looks like this:
from math import ceil
samplestr = "MEET ME MONDAY"
# Pad string to be dividable by 3
samplestr = samplestr.ljust(ceil(len(samplestr)/3) * 3)
# "MEET ME MONDAY "
# Convert to number reprensentation
samplestr = [0 if c == ' ' else (ord(c)-64) for c in samplestr]
# [13, 5, 5, 20, 0, 13, 5, 0, 13, 15, 14, 4, 1, 25, 0]
# Split in chunks of 3
matrix = [samplestr[i:i+3] for i in range(0, len(samplestr), 3)]
print(matrix)
This produces the following output:
[[13, 5, 5], [20, 0, 13], [5, 0, 13], [15, 14, 4], [1, 25, 0]]
Yes, dictionary will make it easier to assign letters to integers but if your final goal is to convert the letters to integer in order like A=1, B=2...Z=26 and " "=0, then assigning indices to the letters will also do the job.
I don't have much knowledge of numpy, so I will do it simply like this:
letterlist2 = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
samplestr = "MEET ME MONDAY "
l = []
s = []
for i in samplestr:
s.append(letterlist2.index(i))
if len(s) == 3:
l.append(s)
s = []
if s != []:
l.append(s)
print(l)
Output:
[[13, 5, 5], [20, 0, 13], [5, 0, 13], [15, 14, 4], [1, 25, 0]]
Use a dictionary (with a single list comprehension) to convert the letters to numbers (would probably be the fastest) and then reshape to have 3 columns (-1 will take care of number of rows):
convert = dict(zip(letterlist, np.arange(27)))
converted = np.array([convert[char] for char in samplestr])
#[13 5 5 20 0 13 5 0 13 15 14 4 1 25]
from math import ceil
#resize to closes upper multiple of 3
converted.resize(ceil(converted.size/3)*3)
#reshape to have 3 columns
converted = converted.reshape(-1,3)
output:
[[13 5 5]
[20 0 13]
[ 5 0 13]
[15 14 4]
[ 1 25 0]]
Here is another solution with a simple dictionary mapping and list comprehensions. Note that you don't need to hardcode letters, it's in the standard library.
from string import ascii_uppercase
chars = " " + ascii_uppercase
encode = {char:"{}".format(i) for i, char in enumerate(chars)}
def str2num(s):
return [[encode[char] for char in s[i:i+3]] for i in range(0, len(s), 3)]
s = "MEET ME MONDAY"
print(str2num(s))
which returns:
[['13', '5', '5'],
['20', '0', '13'],
['5', '0', '13'],
['15', '14', '4'],
['1', '25']]

Join items of a list with '+' sign in a string

I would like my output to be :
Enter a number : n
List from zero to your number is : [0,1,2,3, ... , n]
0 + 1 + 2 + 3 + 4 + 5 ... + n = sum(list)
Yet my actual output is :
Enter a number : 5
List from zero to your number is : [0, 1, 2, 3, 4, 5]
[+0+,+ +1+,+ +2+,+ +3+,+ +4+,+ +5+] = 15
I'm using join as it's the only type I know.
Why are the plus signs printed around the items and why are they surrounding blank spaces?
How should I print the list's values into a string for the user to read ?
Thank you. Here's my code :
##Begin n_nx1 application
n_put = int(input("Choose a number : "))
n_nx1lst = list()
def n_nx1fct():
for i in range(0,n_put+1):
n_nx1lst.append(i)
return n_nx1lst
print ("List is : ", n_nx1fct())
print ('+'.join(str(n_nx1lst)) + " = ", sum(n_nx1lst))
Change each individual int element in the list to a str inside the .join call instead by using a generator expression:
print("+".join(str(i) for i in n_nx1lst) + " = ", sum(n_nx1lst))
In the first case, you're calling str on the whole list and not on individual elements in that list. As a result, it joins each character in the representation of the list, which looks like this:
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'
with the + sign yielding the result you're seeing.
You don't need to call str on your list. That returns the str representation of your list and the output of that is joined with '+'.
You can instead use map to convert each item in your list to str, then join:
print('+'.join(map(str, n_nx1lst)) + " = ", sum(n_nx1lst))
You can also use the new style formatting to have a more readable output:
result = '+'.join(map(str, n_nx1lst))
print("{} = {}".format(result, sum(n_nx1lst)))
What you need to do is concatenate a string element with ' + ' for each element in your list. All you need from there is to have some string formatting.
def sum_of_input():
n = int(raw_input("Enter a number : ")) # Get our raw_input -> int
l = range(n + 1) # Create our list of range [ x≥0 | x≤10 ]
print("List from zero to your number: {}".format(l))
print(' + '.join(str(i) for i in l) + ' = {}'.format(sum(l)))
Sample output:
>>> sum_of_input()
Enter a number : 10
List from zero to your number: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
How does it work?
We use what's called a list comprehension (5.1.3) (generator in this specific usage) to iterate over our list of int elements creating a list of string elements. Now we can use the string method join() to create our desired format.
>>> [str(i) for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
>>> ' + '.join(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'])
'1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10'
Using f-string :
n_put = range(int(input("Choose a number : ")))
res = sum(n_put)
print ("List is : ", [*n_put])
print(*n_put, sep="+", end = f" = {res}")
gives
Choose a number : 5
List is : [0, 1, 2, 3, 4]
0+1+2+3+4 = 10

Using raw_input in python for lists

I am trying to use raw_input in the python code to get user input of lists as below.
input_array.append(list(raw_input()));
User input as:
1 2 3 5 100
But the code is interpreting input as
[['1', ' ', '2', ' ', '3', ' ', '5', ' ', '1', '0', '0']]
Try: If I use plain input() instead of raw_input(), I am facing the issue in console.
"SyntaxError: ('invalid syntax', ('<string>', 1, 3, '1 2 3 4 100'))"
Note: I am not allowed to give the input in list format like
[1,2,3,5,100]
Could somebody please tell me how to proceed further.
>>> [int(x) for x in raw_input().split()]
1 2 3 5 100
[1, 2, 3, 5, 100]
>>> raw_input().split()
1 2 3 5 100
['1', '2', '3', '5', '100']
Creates a new list split by whitespace and then
[int(x) for x in raw_input().split()]
Converts each string in this new list into an integer.
list()
is a function that constructs a list from an iterable such as
>>> list({1, 2, 3}) # constructs list from a set {1, 2, 3}
[1, 2, 3]
>>> list('123') # constructs list from a string
['1', '2', '3']
>>> list((1, 2, 3))
[1, 2, 3] # constructs list from a tuple
so
>>> list('1 2 3 5 100')
['1', ' ', '2', ' ', '3', ' ', '5', ' ', '1', '0', '0']
also works, the list function iterates through the string and appends each character to a new list. However you need to separate by spaces so the list function is not suitable.
input takes a string and converts it into an object
'1 2 3 5 100'
is not a valid python object, it is 5 numbers separated by spaces.
To make this clear, consider typing
>>> 1 2 3 5 100
SyntaxError: invalid syntax
into a Python Shell. It is just invalid syntax. So input raises this error as well.
On an important side note:
input is not a safe function to use so even if your string was '[1,2,3,5,100]' as you mentioned you should not use input because harmful python code can be executed through input.
If this case ever arises, use ast.literal_eval:
>>> import ast
>>> ast.literal_eval('[1,2,3,5,100]')
[1, 2, 3, 5, 100]

Categories

Resources