how to detect a string in a variable - python-3.x

x = input("enter input: ")
if x == "hello":
print ("it does")
How would I detect if x has hello stored even if it has other charaters/strings?

This is as simple as using the in keyword.
x = "123hellomore"
if "hello" in x:
print("Hi there")
This only detects hello, if it is unobstructed so still in one word (not like "**hel*lo")

If entered input is single string then x below will be array of one element, if entered input is space separated strings (string of strings) then x will be array of multiple strings, below code handles both options
x = input("Enter input: ").split()
for y in x:
if y=="hello"
print("it does")

Related

How would I print a string obtained from a user in reverse?

I'm stuck on an exercise where I must obtain a string from a user and then print it in reverse with each letter on its own line. I've done this successfully with a for loop but I was wondering how to do so without it.
user_string = input("Please enter a string: ")
for letter in (user_string)[::-1]:
print(letter)
You can reverse and use str.join to rebuild the string.
print("\n".join(reversed(input("Please enter a string: "))))
If you know how many characters there are in the string or array (calculate using the length method len()) then you could do:
while i < arr_length:
with i incrementing at the end of every round.
The rest of the code would be the same but using i as an index.
One method would be to cast the string to a list and use the list.pop() method until there are no characters left in the list.
user_input = list(input())
while len(user_input) > 0:
print(user_input.pop())
list.pop() will remove the last item in the list and return it.
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "Geeksforgeeks"
print("The original string is : ", end="")
print(s)
print("The reversed string(using loops) is : ", end="")
print(reverse(s))
Using index property we can easily reverse a given string
a = input()
print(a[::-1])

I want to compress each letter in a string with a specific length

I have the following string:
x = 'aaabbbbbaaaaaacccccbbbbbbbbbbbbbbb'. I want to get an output like this: abaacbbb, in which "a" will be compressed with a length of 3 and "b" will be compressed with a length of 5. I used the following function, but it removes all the adjacent duplicates and the output is: abacb :
def remove_dup(x):
if len(x) < 2:
return x
if x[0] != x[1]:
return x[0] + remove_dup(x[1:])
return remove_dup(x[1:])
x = 'aaabbbbbaaaaaacccccbbbbbbbbbbbbbbb'
print(remove_dup(x))
It would be wonderful if somebody could help me with this.
Thank you!
Unless this is a homework question with special constraints, this would be more conveniently and arguably more readably implemented with a regex substitution that replaces desired quantities of specific characters with a single instance of the captured character:
import re
def remove_dup(x):
return re.sub('(a){3}|([bc]){5}', r'\1\2', x)
x = 'aaabbbbbaaaaaacccccbbbbbbbbbbbbbbb'
print(remove_dup(x))
This outputs:
abaacbbb

Python string comparison function with input, while loop, and if/else statment

I'm trying to create a program that takes input from the user, -1 or 1 to play or quit, number of characters (n), two words for comparison (s1,s2), and calls this function: def strNcompare (s1,s2,n) and then prints the result. The function should return 0,-1,1 if n-character portion of s1 is equal to, less than, or greater than the corresponding n-character of s2, respectively. So for example is the first string is equal to the second string, it should return a 0.
The loop should end when the user enters, -1.
I'm just starting out in Python so the code I have is pretty rough. I know I need an if/else statement to print the results using the return value of the function and a while loop to make the program run.
This is what I have so far, it by no means works but my knowledge ends here. I don't know how to integrate the character (n) piece at all either.
com = input ("String comparison [1(play), -1(quit)]: ")
while (com=='1'):
s1 = input ("enter first string: ")
s2 = input ("enter second string: ")
n = int(input("number of characters: ")
s1 = s1[:n]
s1 = s2[:n]
if com==-1:
break
def strNcompare(s1,s2,n):
return s1==s2
elif s1==s2:
print(f'{s1} is equal to {s2}')
elif s1>s2:
print (f'{s1} is greater than {s2}')
elif s1<s2:
print (f'{s1} is less than {s2}')
else:
print ("QUIT")
break
com = input ("String comparison [1(play), -1(quit)]: ")
As of 10/05/2019 - I revised the code and now I am getting a syntax error at "s1 = s1[:n]"
it did not made much sense and especially the variable 'n' is not completely clear to me. I would not code it like that but I tried to be as close to your logic as possible.
com = input ("String comparison [1(play), -1(quit)]: ")
while (com=='1'):
s1 = input ("enter first string: ")
s2 = input ("enter second string: ")
n = input ("number of characters: ") #what is the purpose of this?
if s1==s2:
print(f'{s1} is equal than {s2}')
elif s1>s2:
print (f'{s1} is greater than {s2}')
elif s1<s2:
print (f'{s1} is less than {s2}')
else:
print ("Error")

python function call not printing as expected

So I have 2 functions - displayHand(hand) and calculateHandlen(hand)
def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ")
print()
def calculateHandlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer
"""
handLen = 0
for i in hand:
handLen = handLen + hand.get(i,0)
return handLen
There's a loop in another function that is dependent on the above functions -
def playHand(hand, wordList, n):
"""
hand = dictionary
wordList = list of valid words
n = an integer passed while function call
"""
totalscore = 0
while(calculateHandlen(hand)>0):
print("Current Hand: " +str(displayHand(hand)))
newWord = input('Enter word, or a "." to indicate that you are finished: ')
Function call for playHand() is as follows:
wordList = loadWords() #loadWords could be a list of words
playHand({'n':1, 'e':1, 't':1, 'a':1, 'r':1, 'i':2}, wordList, 7)
I'm expecting the output to be:
Current Hand: n e t a r i i
Enter word, or a "." to indicate that you are finished:
However, it displays the following:
n e t a r i i
Current Hand: None
Enter word, or a "." to indicate that you are finished:
Don't know where I'm going wrong.
Note: I'm not allowed to make any changes to the first 2 functions.
displayHand() doesn't return anything, so the default None is returned. When you call it, it prints the output directly.
If you are not allowed to alter displayHand(), you need to print your label first, then call the function:
print("Current Hand: ", end='')
displayHand(hand)
The end='' removes the newline print() would normally write.

Combining two strings to form a new string

I am trying to write a program that asks the user for two strings and creates a new string by merging the two together (take one letter from each string at a time). I am not allowed to use slicing. If the user enters abcdef and xyzw, program should build the string: axbyczdwef
s1 = input("Enter a string: ")
s2 = input("Enter a string: ")
i = 0
print("The new string is: ",end='')
while i < len(s1):
print(s1[i] + s2[i],end='')
i += 1
The problem I am having is if one of the strings is longer than the other I get an index error.
You need to do your while i < min(len(s1), len(s2)), and then make sure to print out the remaining part of the string.
OR
while i < MAX(len(s1), len(s2)) and then only print s1[i] if len(s1) > i and only print s2[i] if len(s2) > i in your loop.
I think zip_longest in Python 3's itertools gives you the most elegant answer here:
import itertools
s1 = input("Enter a string: ")
s2 = input("Enter a string: ")
print("The new string is: {}".format(
''.join(i+j for i,j in itertools.zip_longest(s1, s2, fillvalue=''))))
Here's the docs, with what zip_longest is doing behind the scenes.

Resources