Python Forum
testing indivudual string for alternating characters
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
testing indivudual string for alternating characters
#1
I have an assignment where I need to test strings and only accept the strings that have the same two alternating characters throughout the string... i.e. if the characters were 'a' and 'b' I could only accept strings that are ababab or bababa. My code so far looks like this and I have no clue why it doesn't work or what I am doing wrong.


if string[0:len(string):2] != string[1:len(string):2]:
return string

in my mind, the above code means if the given string, starting at 0, and going the length of the string, every other character, does not equal the string, starting at 1, for the length of the string, and going every other character then it should have alternating characters for the entire length of the string, but it doesn't work.. It does return strings that alternate 'abababa', but also returns strings like 'aababababbbbb' as long as they have both letters it returns them. I am just extremely confused, clearly my logic on this isn't correct. Any guidance would be greatly appreciated!
Reply
#2
You have way oversimplified the checking for condition. Condition will be true as soon as the two ("sub")strings aren't equal, and that is very easy to achieve, so it won't suffice to get the result you want.
You need to check that elements in both sliced strings are all the same.
Reply
#3
thank you for the reply. I have done away with the previous idea and am now onto this... still no luck in figuring it out. My messed up logic behind this one is the same as the last... frustrated!

for char in range(0, len(string), 2):
for char2 in range(1, len(string), 2):
if char != char2:
return string
Reply
#4
Please put your code in Python code tags, it is required for the code to be displayed in a readable manner. You can find help here.
I suggest you start on the other end. Think of a couple of example words you would pass to your program and what result you want it to give. Then find a way to solve the problem mentally (find procedure/algorithm, can use pen and paper of course), as if there was no computer to help you. After you succeed, turn the procedure you got into code.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with extracting characters from string valentino1337 2 529 Feb-19-2024, 01:17 PM
Last Post: Pedroski55
  Replacing a few characters of a specified character but not all of them from a string fatherted99 7 3,270 Aug-13-2020, 09:08 AM
Last Post: fatherted99
  Counting the number of occurrences of characters in a string nsadams87xx 1 1,943 Jun-16-2020, 07:22 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020