Python 3.x replace() with index [duplicate] - python

This question already has answers here:
Changing one character in a string
(15 answers)
Closed 2 years ago.
A question I came up with:
I'm trying to write a function that replaces the first and the fourth letter of a word with the same letter just capitalized.
Currently I am working with the string.replace() method. It works great for most of the time, except when there is an equal letter to the one on the fourth place before it.
Example: "bananas"
What I would expect the program to do is to return "BanAnas" but for a reason it return "BAnanas". If I use the word "submarine" it would just work fine, "SubMarine".
The code I wrote is this:
def old_macdonald(name):
name = name.replace(name[0], name[0].upper(), 1)
name = name.replace(name[3], name[3].upper(), 1)
return name
Can someone explain why this is happening?

It's because name.replace(name[3], name[3].upper(), 1) looks for the first character matching name[3]. Stop using replace altogether, chop up your string by slicing.

Related

How to use str.startswith with multiple strings? [duplicate]

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.

How can I write the whole word of the variable, in Python? [duplicate]

This question already has answers here:
Converting a String to a List of Words?
(15 answers)
Split a string with unknown number of spaces as separator in Python [duplicate]
(6 answers)
Closed 2 years ago.
I want to be able to print the whole variable, or just detect it. If I run it through a for loop as I've done in the code below, it just prints the individual letters. How can it print the whole word?
Question = input()
Answer = input()
def test():
for words in Answer:
print(words)
test()
Since answer is a string, and a string is an enumerable type, it enumerates over the characters. If you want to print a plain string just do print(Answer).
This would work perfectly
Question = input()
Answer = input()
def test():
for words in Answer.split(' '):
print(words)
test()
When you are iterating a string in python what it does, it makes an iterable out of a string and then it print's each letter in a given word. This is for both single word and multiple words, so either you can just print(Answer) or you can first split it by e.g. space and then print each word in a sentence like this:
answer = Answer.split() # splits by space, you can provide any separator and this will generate a list for you
for word in answer:
print(word)
This will print each word even if it's only 1.
This is a poorly phrased question and poorly researched question which can get you banned from asking questions in Stack overflow so keep that in mind when you post another question.
You can do
for word in Answer.split(" "):
print(word)
If that's not what you are looking for you can try-
print(Answer)

How to run a statement again and again on a case but on different occurrences [duplicate]

This question already has answers here:
Replace characters in string from dictionary mapping
(2 answers)
Closed 2 years ago.
Hey guys I am making an encoding system in which each letter gets converted into predefined gibberish.
For example, 'a' has already been set as 'ashgahsjahjs'.
But using if a in data: print("ashgahsjahjs") executes this for one time only, if there are more than one A in the word, it would not print them with gibberish.
Using a while loop does not work either as it keeps printing indefinitely, so is there a way to print the gibberish each time there is a new occurrence of a letter.
you could try indexing the string.
your_string = "are you an apple?"
for i in range(len(your_string)):
if "a" == your_string[i]:
print("Found a at position {pos}".format(pos=i))
else:
print("Nope")

How to delete the last character in a string in python 3 [duplicate]

This question already has answers here:
Remove final character from string
(5 answers)
Closed 4 years ago.
I'm trying to delete the last character of a string, and every documentation I can find says that this works.
string = 'test'
string[:-1]
print(string)
However, whenever I try it, my IDE tells me that line two has no effect, and when I run the code it outputs "test" and not "tes", which is what I want it to do. I think that the documentation I'm reading is about python 2 and not 3, because I don't understand why else this simple code wouldn't work. Can someone show me how to remove the last letter of a string in python 3?
new_string = string[:-1]
print(new_string)
You must save the string in the memory. When we assign a variable to the string without the last character, the variable then "stores" the new value. Thus we can print it out.

Trying to compare palindrome string in python [duplicate]

This question already has answers here:
How to check for palindrome using Python logic
(35 answers)
Closed 7 years ago.
I'm trying to compare a string and check if it is palindrome or not. I'm using the next method:
name = input("Enter your string")
name1 = name[-1::-1]
if(name==name1):
print("True")
else:
print("False")
but it always shows me False
has anyone idea why its not working properly?
Because you are starting at the last character of the string. You want to use name[::-1] instead. That will take the entire string from beginning to end with a step of -1, meaning that it will be reversed.

Categories