I understand how to normally slice a string and reverse it, but don't get how to do both simultaneously.
Let's say
message="hi there"
And I wanna select only the "there" part and reverse it, so the output will be "ereht".
Is there a way to do it? Preferably using only the "message" variable, but any other ways are ok, too.
You would split the string and then reverse it part you desire
rev = message.split()[-1][::-1]
This solution will also work for the example given in the OP (credit to Kelly Bundy):
rev = message[:-6:-1]
For your specific question, you can use this:
message.split()[-1][::-1]
You just need to select the second slice with [1] and then reverse it using [::-1]
message.split()[1][::-1]
Related
Say I have a string "abcde", and want to get "deab". How can I get "deab" using string slicing?
I've tried using string[-2:1], but this gives me an empty result ''.
The project I am working on makes splitting this up into [-2:] and [:2] difficult, hence the question. Thanks!
You can simulate wrapping by doubling the string:
(string * 2)[3:7]
This is not necessarily much less efficient than getting two slices the usual way: it only creates one temporary string instead of two, but obviously requires quite a bit more space.
You may want this,
s[-2:] + s[:2]
What is the python syntax to insert a line break after every occurrence of character "X" ? This below gave me a list object which has no split attribute error
for myItem in myList.split('X'):
myString = myString.join(myItem.replace('X','X\n'))
myString = '1X2X3X'
print (myString.replace ('X', 'X\n'))
You can simply replace X by "X\n"
myString.replace("X","X\n")
Python 3.X
myString.translate({ord('X'):'X\n'})
translate() allows a dict, so, you can replace more than one different character at time.
Why translate() over replace() ? Check translate vs replace
Python 2.7
myString.maketrans('X','X\n')
A list has no split method (as the error says).
Assuming myList is a list of strings and you want to replace 'X' with 'X\n' in each once of them, you can use list comprehension:
new_list = [string.replace('X', 'X\n') for string in myList]
Based on your question details, it sounds like the most suitable is str.replace, as suggested by #DeepSpace. #levi's answer is also applicable, but could be a bit of a too big cannon to use.
I add to those an even more powerful tool - regex, which is slower and harder to grasp, but in case this is not really "X" -> "X\n" substitution you actually try to do, but something more complex, you should consider:
import re
result_string = re.sub("X", "X\n", original_string)
For more details: https://docs.python.org/2/library/re.html#re.sub
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reverse a string in Python
Its been stumping me despite my initial thoughts that it would be simple.
Originally, I thought I would have have it print the elements of the string backwards by using slicing to have it go from the last letter to the first.
But nothing I've tried works. The code is only a couple lines so I don't think I will post it. Its extraordinarily frustrating to do.
I can only use the " for ", "while", "If" functions. And I can use tuples. And indexing and slicing. But thats it. Can somebody help?
(I tried to get every letter in the string to be turned into a tuple, but it gave me an error. I was doing this to print the tuple backwards which just gives me the same problem as the first)
I do not know what the last letter of the word could be, so I have no way of giving an endpoint for it to count back from. Nor can I seem to specify that the first letter be last and all others go before it.
You can do:
>>> 'Hello'[::-1]
'olleH'
Sample
As Mike Christensen above wrote, you could easily do 'Hello'[::-1].
However, that's a Python-specific thing. What you could do in general if you're working in other languages, including languages that don't allow for negative list slicing, would be something more like:
def getbackwards(input_string):
output = ''
for x in range(0,len(input_string),-1):
output += input_string[x]
return output
You of course would not actually do this in Python, but just wanted to give you an example.
i am trying to select the elements of a list without the very first element. the following code works but it kinda look ugly to me
[s[i] for i in range(len(s)) if i>0]
is there a better way to write it? thanks
Use the slicing notation:
s[1:]
Alternatively, you can avoid copying the list thus:
itertools.islice(s, 1, None)
The result isn't a list — it doesn't support random access, for instance — but you can pass it to anything that accepts an iterator.
Wouldn't s[1:] be correct?
In Python, if I want to get the first n characters of a string minus the last character, I do:
output = 'stackoverflow'
print output[:-1]
What's the Ruby equivalent?
I don't want to get too nitpicky, but if you want to be more like Python's approach, rather than doing "StackOverflow"[0..-2] you can do "StackOverflow"[0...-1] for the same result.
In Ruby, a range with 3 dots excludes the right argument, where a range with two dots includes it. So, in the case of string slicing, the three dots is a bit more close to Python's syntax.
Your current Ruby doesn't do what you describe: it cuts off the last character, but it also reverses the string.
The closest equivalent to the Python snippet would be
output = 'stackoverflow'
puts output[0...-1]
You originally used .. instead of ... (which would work if you did output[0..-2]); the former being closed–closed the latter being closed–open. Slices—and most everything else—in Python are closed–open.
"stackoverflow"[0..-2] will return "stackoverflo"
If all you want to do is remove the last character of the string, you can use the 'chop' method as well:
puts output.chop
or
puts output.chop!
If you only want to remove the last character, you can also do
output.chop