This question already has answers here:
How would you make a comma-separated string from a list of strings?
(15 answers)
Closed 6 years ago.
I'm new to python, and have a list of longs which I want to join together into a comma separated string.
In PHP I'd do something like this:
$output = implode(",", $array)
In Python, I'm not sure how to do this. I've tried using join, but this doesn't work since the elements are the wrong type (i.e., not strings). Do I need to create a copy of the list and convert each element in the copy from a long into a string? Or is there a simpler way to do it?
You have to convert the ints to strings and then you can join them:
','.join([str(i) for i in list_of_ints])
You can use map to transform a list, then join them up.
",".join( map( str, list_of_things ) )
BTW, this works for any objects (not just longs).
You can omit the square brackets from heikogerlach's answer since Python 2.5, I think:
','.join(str(i) for i in list_of_ints)
This is extremely similar, but instead of building a (potentially large) temporary list of all the strings, it will generate them one at a time, as needed by the join function.
and yet another version more (pretty cool, eh?)
str(list_of_numbers)[1:-1]
Just for the sake of it, you can also use string formatting:
",".join("{0}".format(i) for i in list_of_things)
Related
This question already has answers here:
Python Remove Comma In Dollar Amount
(4 answers)
Closed 2 years ago.
I can't perform any math operations on these values that I had exported. I'm using xlwt library to do this. Any way to convert these values in the format so that I can be able to perform math operations on it.
float('3629,473.237'.replace(',', ''))
You can replace the commas, they make no sense except readablity
n = float("3629,473.237".replace(",",""))
To re-add commas as string, you can use format strings:
print("{:,}".format(n))
There are f-strings in python 3.6+
print(f"{n:,}")
No; you'll have to remove the comma manually.
float("123,000.12".replace(',',''))
If you have consistent data, you might as well remove all the commas and convert the result.
This question already has answers here:
Which is the preferred way to concatenate a string in Python? [duplicate]
(12 answers)
Closed 4 years ago.
I am trying to append a set of objects combined into one as a single object on the end of a list. Is there any way I could achieve this?
I've tried using multiple arguments for .append and tried searching for other functions but I haven't found any so far.
yourCards = []
cards =["Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"]
suits = ["Hearts","Diamonds","Clubs","Spades"]
yourCards.append(cards[random.randint(0,12)],"of",suits[random.randint(0,3)])
I expected the list to have a new element simply as "Two of Hearts" etc. but instead I recieve this error:
TypeError: append() takes exactly one argument (3 given)
You are sending append() multiple arguments not a string. Format the argument as a string as such. Also, random.choice() is a better approach than random.randint() here as stated by: #JaSON below.
3.6+ using f-strings
yourCards.append(f"{random.choice(cards)} of {random.choice(suites)}")
Using .format()
yourCards.append("{} of {}".format(random.choice(cards), random.choice(suites)))
string concatenation
yourCards.append(str(random.choice(cards)) + " of " + str(random.choice(suites)))
#You likely don't need the str() but it's just a precaution
Improving on Alex's join() approch
' of '.join([random.choice(cards), random.choice(suites)])
yourCards.append(' '.join([random.choice(cards), "of", random.choice(suits)]))
This question already has answers here:
How to convert string representation of list to a list
(19 answers)
Closed 5 years ago.
I have some problems with using a list in python.
Right now, I open a .txt file with data, and read it into my python file.
However, when I put the input from the datafile into variable data and print this to check if it works or not, I see a lot of extra brackets which I don't want. Right now, it looks like:
["['sports','pizza','other']"]
and I want it to have it in a way like this:
['sports','pizza','other']
Can someone help me to get this work? Reason why I want it in a format like I mentioned above, is that I want to compare the list with another list, and that does not work in the format with the ]"]
I hope someone will help me.
Simply use eval function from Python.
>>> a = ["['sports','pizza','other']"]
>>> eval(a[0])
['sports', 'pizza', 'other']
This question already has answers here:
Python- Turning user input into a list
(3 answers)
Create a tuple from an input in Python
(5 answers)
Closed 10 months ago.
Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers.
values = input("Input some comma separated numbers : ")
list = values.split(",")
tuple = tuple(list)
print('List : ',list)
print('Tuple : ',tuple)
This does work but is there any other easier way?
If you're looking for a more efficient way to do this, check out this question:
Most efficient way to split strings in Python
If you're looking for a clearer or more concise way, this is actually quite simple. I would avoid using "tuple" and "list" as variable names however, it is bad practice to name variables as their type.
Well, the code that you have written is pretty concise but you could remove few more line by using the below code:
values = input("Enter some numbers:\n").split(",")
print(values) #This is the list
print(tuple(values)) #This is the tuple
This question already has answers here:
How can I make a dictionary (dict) from separate lists of keys and values?
(21 answers)
Closed 8 years ago.
With two lists of different sizes:
numbers=[1,2,3,4,5]
cities=['LA','NY','SF']
I need to get this:
result={1:'LA', 2:'NY', 3:'SF'}
I thought of doing it with:
result={number:cities[numbers.index(number)] for number in numbers if numbers.index(number)<len(cities)}
But this one-liner gets kind of long. I wonder if there is an alternative way of achieving the same goal.
EDITED LATER:
There were multiple suggestions made to use zip:
dict(zip(cities, numbers))
While it is a definitely a simpler syntax than list comprehension I've used I wonder which would be faster to execute?
Use zip, it will only zip upto the end of the shortest sequence
dict(zip(cities, numbers))
numbers=[1,2,3,4,5]
cities=['LA','NY','SF']
dict(zip(cities,numbers))
;)
I suspect it is duplicate though - search before you post
The easiest is probably dict(zip(numbers,cities))
zip will stop once any of the lists ends, which is what you want.