list with numbers and strings to single string python - python

How do I print a list that has numbers and strings to a single string?
For example, I have this list: ["(",3,"+",4,"-",3,")"], I would like it to be printed as :(3+4-4). I tried to use the join command, but I keep having issues with the numbers.

You have to cast the ints to str, str.join expects strings:
l = ["(",3,"+",4,"-",3,")"]
print("".join(map(str,l)))
(3+4-3)
Which is equivalent to:
print("".join([str(x) for x in l]))
To delimit each element with a space use:
print(" ".join(map(str,l)))

Related

how to assign string input as list in python

User is giving list as input [1,2,3,4]:
a = input()
It is taking this as str.
I want to get this data into local list b.
b = a.strip('][').split(', ')
print(b)
Output: ['1,2,3,4']
How to get list individually not a single entity?
You should do .split(',') instead of .split(', ')
You can use ast.literal_eval to do so.
import ast
a = input()
b = ast.literal_eval(a)
print(b)
# output
[1, 2, 3, 4]
From the docs:
Safely evaluate an expression node or a string containing a Python
literal or container display. The string or node provided may only
consist of the following Python literal structures: strings, bytes,
numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis.
This can be used for safely evaluating strings containing Python
values from untrusted sources without the need to parse the values
oneself. It is not capable of evaluating arbitrarily complex
expressions, for example involving operators or indexing.
the problem is that in the line:
b = a.strip('][').split(', ')
you used ', ' with whitespace instead of ',' without whitespace
because your input does not have any spaces as shown below:
user is giving list as input [1,2,3,4]
ast.literal_eval(a) gets the string input as a list datatype, which can be converted into a list of individual strings with map:
import ast
b = list(map(str,ast.literal_eval(a)))
['1', '2', '3', '4']

Converting a string separated by commas to a list of floats

In Python, I currently have a one element list of elements given like so:
x= ['1.1,1.2,1.6,1.7']
where each of the values are only separated by commas. I want to make this a list of floats, e.g like
x=[1.1, 1.2, 1.6, 1.7]
I've tried x=[float(i) for i in x] and x=[float(i) for i in x.split()], but both return errors.
x is a list with one string, so to access that string you need x[0]. That string is comma-separated, so you need to specify the delimiter: split(','). (Otherwise, split() tries to split a string on whitespace, as described in the docs.)
So you end up with:
[float(i) for i in x[0].split(',')]
You can use map() like this:
list(map(float, x[0].split(',')))
map() takes a function (float in our case) and an iterable ( in our case this list: x[0].split(',')). float function is called for each item of our list x[0].split(',')
It is equivalent to this list comprehension:
[float(item) for item in x[0].split(',')]
Split the string by commas, and construct a float from each item:
[ float(item) for item in '1.1,2.3,5.1'.split(',') ]
Make sure you are applying your split() function on a string and not the single element list. Use x[0] to ensure that. Also, pass a separator , to the split() function.
x = [float(i) for i in x[0].split(',')]
x=[float(i) for i in x.split()] is almost correct, except for two things. For one, you're not passing in anything to the split() function, so it's not going to split anything in your string (it would split only on whitespace, which your string does not have). You want to split by commas, so you have to pass a comma to it, like x.split(',').
Second, seeing as x is defined by x= ['1.1,1.2,1.6,1.7'], which is a list containing a single string, you would have to refer to the string in the array with x[0]. The final code would look like this:
x = ['1.1,1.2,1.6,1.7']
floats = [float(i) for i in x[0].split(',')]
print(floats)
This outputs a list of floats: [1.1, 1.2, 1.6, 1.7]
If x were just a string, like x = '1.1,1.2,1.6,1.7', then you would simply use floats = [float(i) for i in x.split(',')].

Add a number to the beginning of a string in particular locations

I have this string:
abc,12345,abc,abc,abc,abc,12345,98765443,xyz,zyx,123
What can I use to add a 0 to the beginning of each number in this string? So how can I turn that string into something like:
abc,012345,abc,abc,abc,abc,012345,098765443,xyz,zyx,0123
I've tried playing around with Regex but I'm unsure how I can use that effectively to yield the result I want. I need it to match with a string of numbers rather than a positive integer, but with only numbers in the string, so not something like:
1234abc567 into 01234abc567 as it has letters in it. Each value is always separated by a comma.
Use re.sub,
re.sub(r'(^|,)(\d)', r'\g<1>0\2', s)
or
re.sub(r'(^|,)(?=\d)', r'\g<1>0', s)
or
re.sub(r'\b(\d)', r'0\1', s)
Try following
re.sub(r'(?<=\b)(\d+)(?=\b)', r'\g<1>0', str)
If the numbers are always seperated by commas in your string, you can use basic list methods to achieve the result you want.
Let's say your string is called x
y=x.split(',')
x=''
for i in y:
if i.isdigit():
i='0'+i
x=x+i+','
What this piece of code does is the following:
Splits your string into pieces depending on where you have commas and returns a list of the pieces.
Checks if the pieces are actually numbers, and if they are a 0 is added using string concatenation.
Finally your string is rebuilt by concatenating the pieces along with the commas.

Converting a list of nested strings into a nested list of strings

I was wondering how to convert a list of nested strings into a nested list of strings using string manipulation like .split(), .strip(), and .replace(). A sample would be converting a sequence like (notice the single quote with double quotes):
['"Chipotle"', '"Pho"']
into something like:
[["Chipotle"], ["Pho"]]
If your nested strings are in the form of '"A","B","C"', you can use the following:
s.split('"')[1::2] split by double quote, only odd indices (i.e. between quotes)
If you want a nested list, you can use this expression inside a list comprehension, like this:
[s.split('"')[1::2] for s in thelist]
where thelist is the original list.
Why only odd indices? It comes from the structure of the string:
0th element of split() result would be part of the string before 1st quote;
1st - between the 1st and 2nd quotes;
2nd - between the 2nd and 3rd, and so on.
We need only the strings between odd (opening) and even (closing) quotes.
Example:
t = ['"1","2","3","4"', '"5","6","7',"8"']
a = [s.split('"')[1::2] for s in t]
print(a)
prints
[['1','2','3','4'],['5','6','7','8']]

converting a tuple with multiple elements to a string in a list

What would be an easy way to convert:
(1,0,0,0,0,0)
to
['100000']
I know how to switch it to a list using
list()
but i can't figure out how to combine the elements into a string and keep that inside a list.
sep.join(strlist) joins a list of strings together using sep as a separator.
In this case, you will have three steps:
Convert the list of ints to a list of strs, which can be accomplished like so:
strlist = map(str, intlist)
Convert the list of strings to a single string using join.
intstring = "".join(strlist)
Setting the separator = "" will make it squish together to a single string.
Convert the string to a list with a string:
final = [intstring]
Or in one line, as in falsetru's comment:
[''.join(map(str, digits))]

Categories

Resources