Check if the python string contains specific characters - python-3.x

I have to write a program that prompts user for input and should print True only if every character in string entered by the user is either a digit ('0' - '9') or one of the first six letters in the alphabet ('A' - 'F'). Otherwise the program should print False.
I can't use regex for this question as it is not taught yet, i wanted to use basic boolean operations . This is the code I have so far, but it also outputs ABCH as true because of Or's. I am stuck
string = input("Please enter your string: ")
output = string.isdigit() or ('A' in string or 'B' or string or 'C' in string or 'D' in string or 'E' in string or 'F' in string)
print(output)
Also i am not sure if my program should treat lowercase letters and uppercase letters as different, also does string here means one word or a sentence?

We can use the str.lower method to make each element lowercase since it sounds like case is not important for your problem.
string = input("Please enter your string: ")
output = True # default value
for char in string: # Char will be an individual character in string
if (not char.lower() in "abcdef") and (not char.isdigit()):
# if the lowercase char is not in "abcdef" or is not a digit:
output = False
break; # Exits the for loop
print(output)
output will only be changed to False if the string fails any of your tests. Otherwise, it will be True.

Related

Separating a string with large letters into words that begin with the same letters

Suppose you have a string "TodayIsABeautifulDay". How can we get separate it in Python into words like this ["Today", "Is", "A", "Beautiful", "Day"]?
First, use an empty list ‘words’ and append the first letter of ‘word’ to it.
Now using a for loop, check if the current character is in lower case or not, if yes append it to the current string, otherwise, if uppercase, begin a new individual string.
def split_words(word):
words = [[word[0]]]
for char in word[1:]:
if words[-1][-1].islower() and char.isupper():
words.append(list(char))
else:
words[-1].append(char)
return [''.join(word) for word in words]
You can use this function :
word = "TodayIsABeautifulDay"
print(split_words(word))

Write a function that determine if the string is being supplied represents a correctly delimited Python string literal

For the purpose of this function a valid delimiter is the quotation mark(")or the apostrophe('). Correctly delimited strings must use the same delimiter for the beginning and end character, and that delimiter must not be used within the string. Your function should return the result as a Boolean value.
Here are examples of how your function should work.
test1 = input("Enter a test string: ") #user enters: "hello worlds"
print(valid_string(test1)) #True
It's from my previous test and I received a perfect zero. Can someone show me where to start with?
The key to figuring this out is here:
Correctly delimited strings must use the same delimiter for the beginning and end character, and that delimiter must not be used within the string.
You can check that the string begins with a double quote by doing something like my_string[0] == '"', and similarly for the end by doing my_string[-1] == '"'. This works because string[0] and string [-1] will access the first and last characters, respectively. In case you're not aware, negative indexes in Python just mean to start counting from the end (so index -2 would mean the second from the end, etc).
You can then check that no double-quote occurs inside of the string by doing something like this: my_string[1:-1].count('"') == 0. This works because my_string[1:-1] takes the part of the string excluding the first and last character, and then count hte number of times that the double quote occurs (zero- it should never occur).
But wait! The single quote can also be a delimiter! I'll leave that as a challenge for you. Hint: make sure the starting and ending delimiter are the same, and also make sure to allow the other delimiter to occur inside of the string. You should also think about handling edge cases with strings that are 0 or 1 characters long. Let me know if any parts of this answer don't make sense or if you would like clarification on something.
Ok this should work:
def valid_string(s):
try:
return s[0] == s[-1] and s[0] in ["'", '"'] and s[0] not in s[1:-1] and len(s) > 1
except:
return False
while True:
test1 = input("Enter a test string: ")
print(valid_string(test1))
This works find for strings less that 2 characters long:
$ ./valid_string2.py
Enter a test string: 'adsdasfd"adfadfs'
True
Enter a test string: 'adsfdsafdfs'adsfasd'
False
Enter a test string: "adsfdasf'adsfads"
True
Enter a test string: "adsfasdf"adfasd"
False
Enter a test string: """
False
Enter a test string: "'"
True
Enter a test string: '"'
True
Enter a test string: a
False
Enter a test string: 'a'
True
Enter a test string: "a'
False
Enter a test string: a'
False
Enter a test string: 'a"
False

How to detect if any letters from second to last character of a word is capitalized in python? word length is unknown

I've tried this code but it didn't work:
word = input("Enter a word to be tested: ")
for character in word:
if character[0] == character.lower() and character[1:] != character.lower:
result = False
print(result)
Your first line is great, we'll just keep it.
word = input("Enter a word to be tested: ")
Now, we don't care about the first character, so let's see if the others are in lowercase, using str.islower().
result = word[1:].islower()
assert result, 'Your string wasn\'t in lowercase from the second char onwards'

How can create a new string from an original string replacing all non-instances of a character

So Let's say I have a random string "Mississippi"
I want to create a new string from "Mississippi" but replacing all the non-instances of a particular character.
For example if we use the letter "S". In the new string, I want to keep all the S's in "MISSISSIPPI" and replace all the other letters with a "_".
I know how to do the reverse:
word = "MISSISSIPPI"
word2 = word.replace("S", "_")
print(word2)
word2 gives me MI__I__IPPI
but I can't figure out how to get word2 to be __SS_SS____
(The classic Hangman Game)
You would need to use the sub method of Python strings with a regular expression for symbolizing a NOT character set such as
import re
line = re.sub(r"[^S]", "_", line)
This replaces any non S character with the desired character.
You could do this with str.maketrans() and str.translate() but it would be easier with regular expressions. The trick is you need to insert your string of valid characters into the regular expression programattically:
import re
word = "MISSISSIPPI"
show = 'S' # augment as the game progresses
print(re.sub(r"[^{}]".format(show), "_", word))
A simpler way is to map a function across the string:
>>> ''.join(map(lambda w: '_' if w != 'S' else 'S', 'MISSISSIPPI'))
'__SS_SS____'

How to keep the vowel at the beginning of all the words in a string, but remove in the rest of the string

def shortenPlus(s) -> "s without some vowels":
for char in s:
if char in "AEIOUaeiou":
return(s.replace(char,""))
I have the taken it out of the entire string. But I can't figure out how to restrict the replace function to everything but the first letter of each word in a string.
Not sure exactly what you're looking for, can you clarify, perhaps give a simple example? None of the words you have in your example start with vowels!
But here you could remove all the vowels in a word except the first vowel of the first word. Hard coded but gives you an idea:
s="without some vowels"
for char in s[2:]:
if char in "AEIOUaeiou":
s=s.replace(char,"")
print(s)
Outputs
witht sm vwls
Alternatively, to get the first char of every word, you could use a sentinel value that flags each time a non-alpha char such as punctuation or a space is present, then keeps the next char but not the others.
s="without some vowels"
sent=2
for char in s:
if sent>0:
sent-=1
print(char)
continue
if not char.isalpha():
sent=2
continue
s=s.replace(char,"")
print(output)
Outputs
w s v
def shortenPlus(s):
counter = 0 # accepted character count
add_the_vowel = True # check if vowel came for the first time for the word
temp = " " # temp string to store the output
for letter in s:
if letter == " ":
add_the_vowel= True
if add_the_vowel == True and letter in "AEIOUaeiou":
temp += s[counter] # first vowel of the word
if letter in "AEIOUaeiou":
add_the_vowel = False # restrict second vowel appeared
else:
temp += s[counter]
counter += 1
print(temp)
s = "without some vowels frienis"
shortenPlus(s)
How to keep the vowel at the beginning of all the words in a string, but remove in the rest of the string
output :
witht som vowls frins

Resources