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]
Related
This question already has answers here:
str.startswith with a list of strings to test for
(3 answers)
Closed 1 year ago.
I've tried using the or function to input multiple words for the same output, but it only takes the first word as the input and not the rest. How do I solve this? Thanks!
For instance:
message.content.startswith("hi" or "hey")
only takes in "hi" as an input and not "hey".
I've tried adding the words in to a list and it doesn't work as well. I'm relatively new to coding so i'm sorry in advance if it's a stupid question
You can code like this:
message.content.startswith(("hi", "hey"))
From the Python documentation for str.startswith(prefix[, start[, end]]), I've added emphasis:
Return True if string starts with the prefix, otherwise return
False. prefix can also be a tuple of prefixes to look for. With
optional start, test string beginning at that position. With optional
end, stop comparing string at that position.
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)
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:
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 to get the size of a string in Python?
(6 answers)
Closed 7 years ago.
(New to python and stack overflow)
I was curious if there was a way to count the amount of letters in a string for python. for example:
string="hello"
I just want something to count the letters then output it into a variable for later use.
The following will give the length of a string:
len(string)
In your case, you can assign it:
numLetters = len(string)
This function can be used for other objects besides strings. For additional uses, read the documentation.
Use python function len, i.e.:
size = len(string)
len()
https://docs.python.org/2/library/functions.html#len
DEMO
https://ideone.com/mhpdLi