This is my first time posting so forgive me if it's a little off. I'm having a problem getting my code to index properly. I have to take a sentence and a letter from the user and then state how many times the letter was written in the sentence, while also accounting for upper and lowercase letters
enter image description here
You need to compare userInput[i] with userChar, not userInput, because the string will always be the same whereas with userInput[i] it will give you the current letter.
tho doing:
for letter in userString:
if userChar == letter:
...
if better than
for i in range(len(userString)):
if userChar == userString[i]:
...
Related
Not sure if I clearly describe my question, my original string is:
"1.you are beautiful 2.hello world 3.Thanks!"
I want the output to be:
"1.you are beautiful"
"2.hello world"
"3.Thanks!"
or
"1.you are beautiful
2.hello world
3.Thanks!"
I used split() when the sentence contains comma or period. However, I am thinking if I can write a function by using the number. For example, if type(item)==int then add a line break
Thank you for your help!
Here you go. This will only work for single digit numbers and will work with or without the period.
a='1.you are beautiful 2.hello world 3.Thanks!'
out=''
for ch in a:
if ch.isdigit():
out+='\n'+ch
else:
out+=ch
print(out)
If you want to detect any length number (e.g. 11) you would have to use enumerate(a) and "look ahead" to find the period '.' with another for loop and then add the new line or look into use the re package and Regular Expressions.
I am attempting to limit the character length of my input and then verify whether it is one of the three white characters. Struggling with the final part:
while True:
try:
letter=input("Please enter a character: ") #most intuitive way for me was the assert function but very happy to hear any other ways
assert len(letter) !=1
except AssertionError:
print("Please type only ONE character")
else:
whitespace=["\n"," ","\t"] #i believe the list specification here makes the not in code invalid? believe the two may not be compatible but errors not reached there yet
if whitespace not in letter:
print("Your character in lower case is: "+str(letter).lower())
else:
print("You typed a white space character!")
Welcome to Stackoverflow!
It looks like the error is on the if whitespace not in letter: line. This should actually be the other way around: if item not in list:. You have if list not in item:.
Also, it might help you if I reformat your code a little.
while True:
letter = input('Please enter a character: ')
if len(letter) != 1:
print('Please type only ONE character')
continue
if letter in ['\n', ' ', '\t']:
print("You typed a white space character!")
continue
lowercase_letter = letter.lower()
print(f'Your character in lower case is: {lowercase_letter}')
If you haven't already seen pylint, I'd recommend you take a look at it. It helps you format your code to PEP8 standard. It is also quite good at pointing out some simple errors in your code.
Raising Exceptions are for reporting errors to calling functions - i.e. you can't perform the job the function is supposed to be doing because the input or system state is not as required by the function.
Catching Exceptions is for handling specific errors you know how to handle in a higher level function. So for example, if your trying to read a file and it doesn't exist. In your program that mean the user hasn't set a specific flag in the config file... so you can catch that exception and let the user know how to fix the issue.
Raising an Exception and catching it in the same function (at least in this case) is just a very complicated way of writing an if statement.
When writing an if-else statement, it's a good idea to try and make the if branch positive. Which means avoid if not ...: else: if you can.
In your code, letter is already a string object - so there is no need to create a new string object with str(letter). In python everything is an object, even literals.
The continue statement jumps to the next iteration of the loop. Nothing after the continue is executed in the current iteration of the loop. You could also look at break statement that finishes executing the loop. As an exercise, you could look at adding an extra check to your code to see if the user typed 'quit', and then break. What do you think will happen?
if letter.lower() == 'quit':
break
This would have to be added before the check for single letters otherwise you would never get to this check.
Finally, rather than using string concatenation in your print statement (using str + str). You can use f-strings, format strings as in the example f'Hi my name is {name} and I am from {home}', where name and home are string variables.
Hope this helped!
I'd advise you not to use exceptions because they're very unstable. Instead, I'd use if/else conditions, like this one:
letter = input('Please enter a character: ')
if len(letter) == 1:
if letter in '\n\t ':
print('You typed a white space character!')
else:
print('Your character in lowercase is {}'.format(letter.lower()))
else:
print('Please type only ONE character')```
I'm coding this telegram bot for my clan. The bot should send a reply based on a few words in the text msg. Suppose I type a text in the group containing the words "Thalia" and "love" and I want the bot to respond. The following works.
elif "thalia" in text.lower():
if "love" in text.lower():
reply("I love u too babe <3." "\nBut I love my maker even more ;).")
else:
reply("Say my name!")
msg containing thalia and love
I coded it like this because when I use the "and" or "or" keywords the statement doesn't work and the bot goes crazy. In the above, if I code: elif "thalia" and "love"..... it doesn't work.
If there is another way to code this I would appreciate the tip!
Now I am trying the same technique on more words with "and" and "or" but it doesn't work. If I leave "and" and "or" out it works fine. But of course then I can't use the combinations of words I want with this particular response.
elif "what" or "when" in text.lower():
if "time" or "do" in text.lower():
if "match" in text.lower():
reply ("If you need assistence with matches, type or press /matches")
it triggered the command without the 3 words in one sentence
How can I rewrite this code in a more "professional" way and what do I need to change to get it to work? The bot responds only when the combination of the words are used like in the thalia love code. Instead of when "matches" is used.*
Python is much like natural language but the interpreter cannot fill in what human listeners can. 'a and b in c' must be written out as 'a in c and b in c'.
Before writing the if statements, you should lower case text once, not repeatedly. Then turn it into a set of words, after removing punctuation and symbols, to avoid repeated linear searches of the lower-cased string. Here is an incomplete example for ascii-only input.
d = str.maketrans('', '', '.,!') # 3rd arg is chars to delete
text = set(text.lower().translate(d).split())
Your 'matches' snippet can then be written as follows.
elif (("what" in text or "when" in text) and
("time" in text or "do" in text) and
"match" in text)
reply ("If you need assistence with matches, type or press /matches")
You could also use regular expression matching to do the same thing, but logic statements like the above are probably easier to start with.
Dear stackoverflow users,
Many people encounter situations in which they need to modify strings. I have seen many
posts related to string modification. But, I have not come across solutions I am looking
for. I believe my post would be useful for some other R users who will face similar
challenges. I would like to seek some help from R users who are familiar with string
modification.
I have been trying to modify a string like the following.
x <- "Marcus HELLNERJohan OLSSONAnders SOEDERGRENDaniel RICHARDSSON"
There are four individuals in this string. Family names are in capital letters.
Three out of four family names stay in chunks with first names (e.g., HELLNERJohan).
I want to separate family names and first names adding space (e.g., HELLNER Johan).
I think I need to state something like "Select sequences of uppercase letters, and
add space between the last and second last uppercase letters, if there are lowercase
letters following."
The following post is probably somewhat relevant, but I have not been successful in writing codes yet.
Splitting String based on letters case
Thank you very much for your generous support.
This works by finding and capturing two consecutive sub-patterns, the first consisting of one upper case letter (the end of a family name), and the next consisting of an upper then a lower-case letter (taken to indicate the start of a first name). Everywhere these two groups are found, they are captured and replaced by themselves with a space inserted between (the "\\1 \\2" in the call below).
x <- "Marcus HELLNERJohan OLSSONAnders SOEDERGRENDaniel RICHARDSSON"
gsub("([[:upper:]])([[:upper:]][[:lower:]])", "\\1 \\2", x)
# "Marcus HELLNER Johan OLSSON Anders SOEDERGREN Daniel RICHARDSSON"
If you want to separate the vector into a vector of names, this splits the string using a regular expression with zero-width lookbehind and lookahead assertions.
strsplit(x, split = "(?<=[[:upper:]])(?=[[:upper:]][[:lower:]])",
perl = TRUE)[[1]]
# [1] "Marcus HELLNER" "Johan OLSSON" "Anders SOEDERGREN"
# [4] "Daniel RICHARDSSON"
I just wrote a code with the criteria above, but it doesn't seem to work properly because I either miss a letter at the end or in the middle.
Could anyone please check out my code an tell me what I'm doing wrong. By the way I already checked other threads on this similar problem, but I'm not allowed to use regex or print function.
phrase=('my room is cold')
allSpaces=findstr(' ',phrase);
k=length(allSpaces)
acr=phrase(1:allSpaces(1):allSpaces(k)-1)
Output:
acr= mrms
Change last line to
acr = phrase([1 allSpaces+1])
That way you get the first letter, and then the first after each space.