Hello i have a problem making my validation that forces the user to enter 5 words , currently if they enter a space they can go trough also. Here is my code:
cntr = 0
for x in range(len(this.val)):
if this.val[x]. == ' ' and not this.val[x-1] == ' ' and x != 0:
cntr = cntr + 1
if cntr lt 4:
error(res.Q3error)
words = sentence.split()
if len(words) == 5:
print('good')
Or perhaps add a "is_word" test to apply to "words" using an all() - in case you want to reject numbers or something.
Related
def is_palindrome(input_string):
# We'll create two strings, to compare them
new_string = input_string.strip()
print(new_string)
# Traverse through each letter of the input string
newstringseperated = new_string.split()
n = len(new_string)
if n%2 == 0:
for i in range(n//2 - 1):
if newstringseperated[i] != newstringseperated[n-1-i]:
print("False")
hello = 1
if hello == 1:
print("False")
else:
print("True")
if (n%2) != 0:
for i in range((n-1)//2):
if newstringseperated[i] != newstringseperated[n-1-i]:
hello2 = 1
if hello2 == 1:
print("False")
else:
print("True")
I tried to execute this code on the words "kayak" and "deed".
It is showing index error for both of them. What is the problem here? Can someone help me find the mistake?
You have a number of problems here. As #John says, you want to use n // 2 - 1 rather than n / 2 - 1 so that the result is an integer. If you use re.sub() instead of split(), you can get rid of whitespace in the middle of your input strings and get rid of tabs as well as spaces. The big issue is that splitting the input string to create newstringseperated and using that is messing you up. If you instead operate on new_string directly, your code will work. Another small detail...you can break as soon as you recognize a mismatch. This version of your code does what I think you're expecting:
import re
def is_palindrome(input_string):
# We'll create two strings, to compare them
new_string = re.sub(r'\s+', '', input_string)
print(new_string)
# Traverse through each letter of the input string
# newstringseperated = new_string.split()
n = len(new_string)
if n % 2 == 0:
hello = 0
for i in range(n // 2 - 1):
if new_string[i] != new_string[n - 1 - i]:
hello = 1
break
if hello == 1:
print("False")
else:
print("True")
# Add any non-blank letters to the
# end of one string, and to the front
# of the other string.
if (n % 2) != 0:
hello2 = 0
for i in range((n - 1) // 2):
if new_string[i] != new_string[n - 1 - i]:
hello2 = 1
break
if hello2 == 1:
print("False")
else:
print("True")
is_palindrome("kayak")
is_palindrome("deed")
is_palindrome("abcde")
is_palindrome("abcd")
Result:
kayak
True
deed
True
abcde
False
abcd
False
It is better to not have the two cases (odd vs even lengths) in your code. Here's a way to have just one version of your inner logic:
import re
def is_palindrome(input_string):
new_string = re.sub(r'\s+', '', input_string)
print(new_string)
# Traverse through each letter of the input string
n = len(new_string)
for i in range(n // 2 - 1 + n % 2):
if new_string[i] != new_string[n - 1 - i]:
hello = 1
break
else:
hello = 0
print("False" if hello == 1 else "True")
This produces the same result.
Just reverse the string and test so no looping needed:
def is_palindrome(txt):
txt = txt.replace(' ', '')
return txt == txt[::-1]
First of all, to delete whitespaces, use replace() instead of strip() as it takes care of whitespaces in the middle of the string as well.
Secondly, the bigger problem is the split() method. It creates a list of substrings based on a specific separator and what you are essentially doing is comparing words instead of characters. Honestly, you don't even need this method to check for palindrome, just modifying the code a bit like this should work fine:
def is_palindrome(input_string):
new_string = input_string.replace(" ", "")
n = len(new_string)
for i in range(n // 2):
if new_string[i] != new_string[n - 1 - i]:
print("False")
return False
print("True")
return True
I had to do this on my phone but this should work if your looking for a palindrome:
txt = "hannah"
txt2 = "kayak"
txt3 = "blaat"
def palin(txt):
first_half = len(txt) // 2
start_second_half = first_half -1 if len(txt)%2==0 else first_half
return txt[:first_half] == txt[-1:start_second_half:-1]
print(palin(txt))
print(palin(txt2))
print(palin(txt3))
I'm trying to make it so that my text alternates between upper and lower case like the question ask. It seems to skip 3 in the indexing and I can't figure out why.
sentence = input("Write a sentence")
newList = []
for i in range(len(sentence)):
if sentence[i] != " ":
newList.append(sentence[i])
listJoint = "".join(newList)
newList2 = []
for i in range(len(listJoint)):
if (listJoint.index(listJoint[i]) % 2) == 0:
print(listJoint.index(listJoint[i]))
newList2.append(listJoint[i].upper())
elif (listJoint.index(listJoint[i]) % 2) != 0:
print(listJoint.index(listJoint[i]))
newList2.append(listJoint[i].lower())
print(newList2)
#newListJoint = "".join(newList2)
#print(newListJoint[::-1])
Thanks in advance
List index doesn't go 0 1 2 3 4
The function .index() finds the first occurrence of that letter. 'L' occurs at index 2 and 3 so it would return 2 for both L's.
Iterate through each character of the string and alternate upper/lower methods.
sentence = "Hello"
alternated_sentence = ''
for i, char in enumerate(sentence):
if i % 2:
alternated_sentence += char.upper()
else:
alternated_sentence += char.lower()
print(alternated_sentence)
#hElLo
sentence = input("Write a sentence:")
# Remove spaces (as per your question)
sentence = sentence.replace(' ', '')
# Reverse the string order (as per your question)
sentence = sentence[::-1]
result = []
for i in range(len(sentence)):
if(i%2==1):
result.append(sentence[i].lower())
else:
result.append(sentence[i].upper())
print(''.join(result))
Here's the solution. The above code would give output as follows:
Write a sentence: Hello world
DlRoWoLlEh
I never realised index method referenced the first instance of the character. This works:
sentence = input("Write a sentence")
newList = []
for i in range(len(sentence)):
if sentence[i] != " ":
newList.append(sentence[i])
listJoint = "".join(newList)
newList2 = []
for i, value in enumerate(newList):
if i % 2 == 0:
newList2.append(listJoint[i].upper())
elif i % 2 !=0:
newList2.append(listJoint[i].lower())
newListJoint = "".join(newList2)
print(newListJoint[::-1])
Hy have a string which corresponds to a file location in linux, i want to extract just the part of it that corresponds to the username and that always comes after the 6th forward slash and then store it in a new string variable:
str1 = "/usr/share/nginx/website/orders/jim/17jkyu.xlsx"
n = 0
user = ','
for ch in str1:
if ch == '/':
n += 1
if n == 6:
user.join(ch)
if n == 7:
break
print(user + '\n')
In this case i want to extract jim and put it into the string user.
So far is not working
You can use the split Python built-in function over the / symbol, and select the 7th element:
str1.split('/')[6]
Split the string then pull the index value.
str1 = "/usr/share/nginx/website/orders/jim/17jkyu.xlsx"
user = str1.split('/')[6]
You can check if n=6 and the current char is not /, set user to an empty string and concat the character.
str1 = "/usr/share/nginx/website/orders/jim/17jkyu.xlsx"
n = 0
user = ''
for ch in str1:
if ch == '/':
n += 1
if n == 7:
break
if n == 6 and ch != '/':
user += ch
print(user)
Output
jim
What is the reason why I cannot access a specific line number in the already split string?
a = "ABCDEFGHIJKLJMNOPRSTCUFSC"
barcode = "2"
import textwrap
prazno = textwrap.fill(a,width=5)
podeli = prazno.splitlines()
Here the output is correct:
print(podeli)
ABCDE
FGHIJ
KLJMN
OPRST
CUFSC
However, when I want to split one of the lines e.g podeli[2] by 3 characters the python just ignores that and gives the same output like that split of podeli[2] (line 2) has not occured.
if barcode[0] == '1':
podeli[1] += ' MATA'
elif barcode[0] == '2':
podeli[1] += ' MATA'
for podeli[2] in podeli:
textwrap.fill(podeli[2], width=3)
podeli[2].splitlines()
podeli[2] += ' MATA'
The expected output would be:
ABCDE MATA
FGH MATA
IJ
KLJMN
OPRST
CUFSC
Is there a way to split the line by a certain length and its order number?
Thank you, guys!
You can solve your immediate problem by rebuilding the list, but I fear you have a more general problem that you haven't told us.
if barcode[0] == '1':
podeli[1] += ' MATA'
elif barcode[0] == '2':
podeli[1] += ' MATA'
line2 = textwrap.fill(podeli[2], width=3).splitlines()
podeli = podeli[0:2] + line2 + podeli[3:]
podeli[2] += ' MATA'
Try this, it should split a string you specified by a width of 3:
n = 3
[((podeli[2])[i:i+n]) for i in range(0, len(podeli[2]), n)]
For example I have GolDeNSanDyWateRyBeaChSand and I need to find how many times the word sand appears.
text = input()
text = text.lower()
count = 0
if "sand" in text:
count += 1
print(count)
But the problem is that there is 2 sand in this string and when it found the first one it stops. Im a beginner in the programming.
You can simply use the str.count() method to count how many times a string appears in another string.
text = input()
text = text.lower()
count = text.count("sand")
To find every occurrence of a string pattern inside another string s, even nested occurrences, do the following:
s = "sandsandssands" # your string here
pattern = "sands" # your pattern here
pos = -1
end_of_string = False
while not end_of_string:
pos = s.find(pattern, pos+1)
print(pos)
end_of_string = (pos == -1)
Output
0
4
9
-1
Extending the solution offered by the OP.
The idea is to use find and move to towards the end of the string.
It is clear that count can be used here and the solution below is for educational purpose.
text = 'GolDeNSanDyWateRyBeaChSand'
word = 'sand'
ltext = text.lower()
offset = 0
counter = 0
while True:
idx = ltext.find(word, offset)
if idx == -1:
break
else:
counter += 1
offset = idx + len(word)
print(f'The word {word} was found {counter} times')
output
The word sand was found 2 times