This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Closed 2 years ago.
I tried this code but I don't know how input the characters one per line and how to stop the input sequence with the character 0.
def reverse(string):
if len(string) == 0:
return string
else:
return reverse(string[1:]) + string[0]
a = str(input())
print(reverse(a))
In python you can usually reverse an iterable with [::-1].
It should work on strings as well, I guess. So: 'hello'[::-1] gives 'olleh'.
Related
This question already has answers here:
Understanding slicing
(38 answers)
Changing one character in a string
(15 answers)
Closed 1 year ago.
I know how to replace characters, but I would like to have the instance done once. My code replace's all the characters before.
string = "Forever9999"
string = string[:-4] + string[-4:].replace("9", "1")
Which in the end would be Forever1999, but I get Forever1111
Any help appreciated.
You can pass another paramter to str.replace(old, new[, count]), which is the max count of occurrences you want to replace:
string.replace("9", "1", 1)
# 'Forever1999'
This question already has answers here:
How do I get a substring of a string in Python? [duplicate]
(16 answers)
Remove final character from string
(5 answers)
Closed 1 year ago.
How can I get the last character of this string?
seed_name = "Cocoa"
As shown in the official Python tutorial,
>>> word = 'Python'
[...]
Indices may also be negative numbers, to start counting from the right:
>>> word[-1] # last character
'n'
This question already has answers here:
How do I get a substring of a string in Python? [duplicate]
(16 answers)
How to move the first letter of a word to the end
(3 answers)
Closed 4 years ago.
Let's say I have an input:
SA3213023215
I want to move the SA to the very end of the input.
How can I do this?
Assuming that SA3213023215 is a string (which input is by default), you could use string slicing:
s = "SA3213023215"
s2 = s[2:] + s[:2]
# yields 3213023215SA
This question already has answers here:
replace all characters in a string with asterisks
(4 answers)
Closed 4 years ago.
str0 = input("Enter str: ")
str0 = str0.replace(str0, '_')
print(str0)
I need to replace each one of the characters without using loops or conditions
str0 = input("Enter str: ")
str0 = '_'*len(str0)
print(str0)
Should work. The multiplication puts the right amount of _'s so that all of them are replaced.
This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Closed 7 years ago.
i want to reverse the order of characters in a string
so take strings as arguments
and return s new string with letters of the original string
example - "hello" would return "olleh"
All I have gotten to is:
def reverse(" "):
string = input("Give me a word")
x = ord(string)
print(x)
You can do it like this:
"hello"[::-1]
You can read about extended-slices here