Trying to use multiple arguments for .append, anyway how? [duplicate] - python

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)]))

Related

List converted to string [duplicate]

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)

Pass list items as arguments to method [duplicate]

This question already has answers here:
How to extract parameters from a list and pass them to a function call [duplicate]
(3 answers)
How to split list and pass them as separate parameter?
(4 answers)
Closed 1 year ago.
Assuming i have a method definition like this do_stuff(*arg).
I have a list of values, ['a','b',...]. How best can i pass the values of this list as individual arguments to the do_stuff method as do_stuff('a','b',...) ?
I've unsuccessfully tried using list comprehension - do_stuff([str(value) for value in some_list])
I am hoping i don't have to change do_stuff() to accept a list
Any pointers would be appreciated.
You can pass them using the "*" operator. So an example would be like this:
def multiplyfouritems(a,b,c,d):
return a*b*c*d
multiplyfouritems(*[1,2,3,4])
It's the same syntax, with the *:
do_stuff(*['a','b','c'])

EASY How do I use the count() and capitalize() function? [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 3 years ago.
I am new to Python and stack overflow. How do I use the count and capitalize functions for my strings? The app I am learning from appears to have this mixed up because it dosen't work in vscode.
It seems like the capitalize function call is ignored. What am I doing wrong? If someone could tell me how to use the count function as well I have the same problem. The app I learn from is called Programminz.
This is Python 3
practice = "CaPITalIzE mE proPerLy"
practice.capitalize()
print(practice)
string_name.capitalize()
string_name: It is the name of string of
whose first character we want
to capitalize.
Try to use :
string = "CaPITalIzE mE proPerLy"
capitalized_string = string.capitalize()
print('Old String: ', string)
print('Capitalized String:', capitalized_string)

Alternative Ways to Reverse a String [duplicate]

This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Closed 5 years ago.
While doing a homework question, forgetting that that there is a built-in reverse function for strings, I came up with my own way of reversing strings.
So here it is:
for i in range(len(string)):
reversed = string[i] + reversed
I was wondering if this is an efficient (say, if I have a really long string) and correct way of reversing.
You could compare the timing. It's probably quite inefficient, because you make a new string object on every loop iteration and you loop through each character in the string in a Python loop. The built-in function however uses native C code (CPython).
There's a one-liner: reversed = string[::-1]
However, it's kind of hard to read unless you already know the syntax. So you could always bury it in a function with a more helpful name:
def reverse(string):
return string[::-1]

Turning Input into a list [duplicate]

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

Categories