I want my program to read one character from an input of random string, but when there is a space in the string, I want it to read the next two characters.
For example, if I type H He, I want it to return the value for H, then detect a space then return He. How do I do this?
This code is a small part in school assignment (calculating the molecular mass of random compounds).
string=input('enter:')
pos=0
start=None
for a in string:
if a == 'H':
print(string[start:1])
elif a == ' ':
pos=int(string.find(' '))+1
start=pos
print(string[start:1])
You can split the string with space and then get both the values.
string=input('enter:')
values = string.split(' ')
if len(values) > 1:
print("first char:", values[0])
print("remaining:", values[1])
else:
print("first char: ", values[0])
To split the string without the spaces based on the uppercase letter.
import re
elements = re.findall('[A-Z][^A-Z]*', 'NaCl')
print(elements)
You can create a list for the string which you enter and print the list like below:
string=input('enter:')
l=list(string.split())
for i in l:
print(i)
For your new request
string=input('enter: ')
i=0
l=len(string)
while (i<l):
if(i<l-1):
if(string[i].isupper() and string[i+1].isupper()):
print(string[i])
elif(string[i].isupper() and string[i+1].islower()):
print('{}{}'.format(string[i],string[i+1]))
elif(i==l-1 and string[i].isupper()):
print(string[i])
i=i+1
Also, I was wondering if it was possible to do the same thing but separating using lowercase letters?
For example read 'HHe' as 'H', 'He' or 'NaCl' as 'Na', 'Cl' Sorry this is a bit selfish but I was wondering it it could be done
How about this?
import re
words = [
'HHe',
'NaCl',
]
pattern = re.compile(r'[A-Z][a-z]*')
for word in words:
print(pattern.findall(word))
output:
['H', 'He']
['Na', 'Cl']
Related
I can't quite figure this one out.
I have multiple five letter long strings and I want to compare each of the letters of the strings to a single string, and then to know if any of the Nth letters of the strings are equal to the Nth letter of the string I'm comparing them to, like this:
string_1 = 'ghost'
string_2 = 'media'
string_3 = 'blind'
the_word = 'shine'
if the_word[0] == string_1[0] or the_word[0] == string_2[0] or the_word[0] == string_3[0] or the_word[1] == string_1[1] or the_word[1] == string_2[1]... and so on...
print('The Nth letter of some of the strings is equal to the Nth letter of the_word')
else:
print('None of the letters positions correspond')
If there are multiple strings I want to compare the if statement gets very long so there must be a better way of doing this.
I would also like to know what the corresponding letters are (in this case they would be H (string_1[1] == the_word[1]), I (string_3[2] == the_word[2]) and N (string_3[3] == the_word[3])
If there are more than one corresponding letters I would like the return to be list containing all of the letters.
Also I dont need to know if the corresponding letter was the first or whatever the letters position in the word is, only if there are any (and what) corresponding letters.
I find this kind of hard to explain so sorry for possible confusion, will be happy to elaborate.
Thank you!
IIUC, you can get to what you want using zip -
base_strings = zip(string_1, string_2, string_3)
for cmp_pair in zip(the_word, base_strings):
if (cmp_pair[0] in cmp_pair[1]):
print(cmp_pair[0])
Output
h
i
n
You can extract the logic to a dedicated function and call it over each character of the string to be checked:
string_1 = 'ghost'
string_2 = 'media'
string_3 = 'blind'
the_word = 'shine'
def check_letter(l, i, words):
match = []
for w in words:
if w[i] == l:
match.append(w)
return match
for i in range(len(the_word)):
l = the_word[i]
print("checking letter: {}".format(l))
match = check_letter(l, i, [string_1, string_2, string_3])
if (len(match) > 0):
print("found in: {}".format(match))
else:
print("found in: -")
The above code results in:
$ python3 test.py
checking letter: s
found in: -
checking letter: h
found in: ['ghost']
checking letter: i
found in: ['blind']
checking letter: n
found in: ['blind']
checking letter: e
found in: -
Maybe this answers your question:
strings = ['ghost', 'media', 'blind']
the_word = 'shine'
for s in strings:
check = []
lett = []
for i in range(len(s)):
if s[i] == the_word[i]:
check.append(i)
lett.append(s[i])
if check:
print('The letters {0} (position {1}) of the string {2} match to
the word {3}'.format(lett,check,s,the_word))
else:
print('No match between {0} and {1}'.format(s,the_word))
Well one straight forward way would be the following:
string_1 = 'ghost'
string_2 = 'media'
string_3 = 'blind'
string_4 = 'trenn'
the_word = 'shine'
string_list = [string_1, string_2, string_3]
duplicate_letters_list = []
for string in string_list:
for i in range(5):
if the_word[i] == string[i]:
print(f'{i}th letter is in {string} is a duplicate')
if the_word[i] not in duplicate_letters_list:
duplicate_letters_list.append(the_word[i])
print(duplicate_letters_list)
Output
1th letter is in ghost is a duplicate
2th letter is in blind is a duplicate
3th letter is in blind is a duplicate
['h', 'i', 'n']
I want to create an encryption script that encrypts the string given to it, here's how it went.
# First, I created a list of the string I got
string = '16271'
string_list = []
for letter in string:
string_list.append(letter)
Then, I have a list called encrypt_list which the letters which I want to add in order to encrypt my string.
So, I use the following code to add a random letter from the encrypt_list after each letter/component in the string_list and then join the list and print as a string.
for i in range(0, len(string) - 1):
string_list.insert(for letter in string_list: string_list.index(letter) + 1, encrypt_list[random.randint(0, len(encrypt_list) - 1)])
print("The encrypted string is: ")
print(''.join(string_list))
I expected the output to be: 1A6b2n781 (I bolded the letter to show my actual string in it) But I am getting an error, that I cannot use the for loop in the insert function, and I cannot find another way of doing that, please help. Hope I make my problem clear
Not sure what your encrypted_list looks like, but if it's a list of letters, this would work:
import random
string = '16271'
encrypted_list = ['r', 't', 's', 'o', 'j', 'e']
encrypted_string = ''.join([s + random.choice(encrypted_list) for s in string])
Something like this?
# First, I created a list of the string I got
import random
string = '16271'
string_list = []
for letter in string:
string_list.append(letter)
the_other_list = ['lorem', 'dorem', 'forem', 'borem']
for i in range(0, len(the_other_list)):
the_other_list[i] = string_list[random.randint(0, len(string_list) - 1)] + the_other_list[i]
print(''.join(the_other_list))
Result example: 1lorem2dorem2forem7borem
You can use a for loop, adding one letter to the list at a time, then adding a randomly selected letter immediately afterwards (if we're not processing the last letter in the list). I've used constants from string to define the space of characters to sample from; you can adjust this as you see fit.
This should be simpler than trying to do repeated insertion in the middle of the list (where you'd have to handle memory shifting as you're inserting, plus it'd get slower for larger texts because you'd be attempting to insert in the middle of a list).
# First, I created a list of the string I got
import random
import string
encrypt_text = string.ascii_uppercase + string.ascii_lowercase + string.digits
plaintext = '16271'
letters = []
for index, letter in enumerate(plaintext):
letters.append(letter)
if index != len(plaintext) - 1:
letters.append(random.choice(encrypt_text))
print("The encrypted string is: ")
print(''.join(letters))
Based on how you defined the problem, I would recommend implementing it as a generator:
import random
import string
def _gen_string(s):
alphabet = string.ascii_letters
for c in s:
yield c
yield random.choice(alphabet)
Then you can use that as the basis for your encryption:
def encrypt(s):
return ''.join(_gen_string(s))
encrypt('16271')
# 1J6P2U7Z1i
Of course, this is not really encryption. It's obscurity and obscurity is not a form of security that should be relied upon :-)
How do I pick out the letters in a string like: "first.last".
I want to pick out the f in first, and the l in last.
But I need to make it where when someone inputs something like "quartz.block" I need to get the 'q' and 'b'.
Does anyone have any ideas how?
Use split(".") function. Separate the words where dot (.) is present and print the first letter of the separated words. Your code:
string = input("Enter= ")
words = string.split(".")
for word in words:
print(word[0])
You can try the following:
word = "quartz.block"
first_last = f"{word[0]}{word[word.index('.') + 1]}"
Shakespeare iterator solution:
it = iter('quartz.block')
print([c for c in it
if '.' in it
or '.' not in it])
Output (Try it online!):
['q', 'b']
I'm taking a class in python and now I'm struggling to complete one of the tasks.
The aim is to ask for an input, integrate through that string and print only words that start with letters > g. If the word starts with a letter larger than g, we print that word. Otherwise, we empty the word and iterate through the next word(s) in the string to do the same check.
This is the code I have, and the output. Would be grateful for some tips on how to solve the problem.
# [] create words after "G" following the Assignment requirements use of functions, menhods and kwyowrds
# sample quote "Wheresoever you go, go with all your heart" ~ Confucius (551 BC - 479 BC)
# [] copy and paste in edX assignment page
quote = input("Enter a sentence: ")
word = ""
# iterate through each character in quote
for char in quote:
# test if character is alpha
if char.isalpha():
word += char
else:
if word[0].lower() >= "h":
print(word.upper())
else:
word=""
Enter a sentence: Wheresoever you go, go with all your heart
WHERESOEVER
WHERESOEVERYOU
WHERESOEVERYOUGO
WHERESOEVERYOUGO
WHERESOEVERYOUGOGO
WHERESOEVERYOUGOGOWITH
WHERESOEVERYOUGOGOWITHALL
WHERESOEVERYOUGOGOWITHALLYOUR
The output should look like,
Sample output:
WHERESOEVER
YOU
WITH
YOUR
HEART
Simply a list comprehension with split will do:
s = "Wheresoever you go, go with all your heart"
print(' '.join([word for word in s.split() if word[0].lower() > 'g']))
# Wheresoever you with your heart
Modifying to match with the desired output (Making all uppercase and on new lines):
s = "Wheresoever you go, go with all your heart"
print('\n'.join([word.upper() for word in s.split() if word[0].lower() > 'g']))
'''
WHERESOEVER
YOU
WITH
YOUR
HEART
'''
Without list comprehension:
s = "Wheresoever you go, go with all your heart"
for word in s.split(): # Split the sentence into words and iterate through each.
if word[0].lower() > 'g': # Check if the first character (lowercased) > g.
print(word.upper()) # If so, print the word all capitalised.
Here is a readable and commented solution. The idea is first to split the sentence into a list of words using re.findall (regex package) and iterate through this list, instead of iterating on each character as you did. It is then quite easy to print only the words starting by a letter greater then 'g':
import re
# Prompt for an input sentence
quote = input("Enter a sentence: ")
# Split the sentence into a list of words
words = re.findall(r'\w+', quote)
# Iterate through each word
for word in words:
# Print the word if its 1st letter is greater than 'g'
if word[0].lower() > 'g':
print(word.upper())
To go further, here is also the one-line style solution based on exactly the same logic, using list comprehension:
import re
# Prompt for an input sentence
quote = input("Enter a sentence: ")
# Print each word starting by a letter greater than 'g', in upper case
print(*[word.upper() for word in re.findall(r'\w+', quote) if word[0].lower() > 'g'], sep='\n')
s = "Wheresoever you go, go with all your heart"
out = s.translate(str.maketrans(string.punctuation, " "*len(string.punctuation)))
desired_result = [word.upper() for word in out.split() if word and word[0].lower() > 'g']
print(*desired_result, sep="\n")
Your problem is that you're only resetting word to an empty string in the else clause. You need to reset it to an empty string immediately after the print(word.upper()) statement as well for the code as you've wrote it to work correctly.
That being said, if it's not explicitly disallowed for the class you're taking, you should look into string methods, specifically string.split()
My homework assignment is to Write a program that reads a string from the user and creates a list of words from the input.Create two lists, one containing the words that contain at least one upper-case letter and one of the words that don't contain any upper-case letters.
Use a single for loop to print out the words with upper-case letters in them, followed by the words with no upper-case letters in them, one word per line.
What I know is not correct:
s= input("Enter your string: ")
words = sorted(s.strip().split())
for word in words:
print (word)
Because it only sorts the sequence if the Capitol is in the first character. For this assignment a character could appear any where within a word. Such as, 'tHis is a sTring'.
I was playing around with a solution that looked similar to this, just to see if I could get the words with CAPS out..But it just wasnt working:
s = input("Please enter a sentence: ")
while True:
cap = 0
s = s.strip().split()
for c in s:
if c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
print(c[:cap])
cap += 1
else:
print("not the answer")
break
But a regular expression would probably do a better job than writing out the whole alphabet.
Any help is much appreciated. Needless to say I am new to python.
>>> w = 'AbcDefgHijkL'
>>> r = re.findall('([A-Z])', word)
>>> r
['A', 'D', 'H', 'L']
This can give you all letters in caps in a word...Just sharing the idea
>>> r = re.findall('([A-Z][a-z]+)', w)
>>> r
['Abc', 'Defg', 'Hijk']
Above will give you all words starting with Caps letter. Note: Last one not captured as it does not make a word but even that can be captured
>>> r = re.findall('([A-Z][a-z]*)', w)
>>> r
['Abc', 'Defg', 'Hijk', 'L']
This will return true if capital letter is found in the word:
>>> word = 'abcdD'
>>> bool(re.search('([A-Z])', word))
Hint: "Create two lists"
s= input("Enter your string: ")
withcap = []
without = []
for word in s.strip().split():
# your turn
The way you are using the for .. else in is wrong - the else block is executed when there is no break from the loop. The logic you are trying to do looks like this
for c in s:
if c.isupper():
# s contains a capital letter
# <do something>
break # one such letter is enough
else: # we did't `break` out of the loop
# therefore have no capital letter in s
# <do something>
which you can also write much shorter with any
if any(c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for c in s):
# <do something>
else:
# <do something>
Sounds like regexs would be easier for the first part of the problem (a regex that just looks for [A-Z] should do the trick).
For the second part, I'd recommend using two lists, as that's an easy way to print everything out in one for loop. Have one list of non_upper_words and one of upper_words.
So, the basic outline of the program would be:
split the string into an array of words.
for each word in array: if regex returns true, add to upper_words. Else: add to non_upper_words.
print each word in the first array and then in the second.
I wrote this out in pseudo-code because it's a programming assignment, so you should really write the actual code yourself. Hope it helps!
You can use isupper method for your purpose:
text = 'sssample Text with And without'
uppers = []
lowers = []
# Note that loop below could be modified to skip ,.-\/; and etc if neccessary
for word in text.split():
uppers.append(word) if word[0].isupper() else lowers.append(word)
EDITED: You can also use islower method the following way:
text = 'sssample Text with And without'
other = []
lowers = []
# Note that loop below could be modified to skip ,.-\/; and etc if neccessary
for word in text.split():
lowers.append(word) if word.islower() else other.append(word)
OR depends on what you really need you can take a look at istitle method:
titled = []
lowers = []
for word in text.split():
titled.append(word) if word.istitle() else lower.append(word)
AND with simple if else statement:
titled = []
lowers = []
for word in text.split():
if word.istitle():
titled.append(word)
else:
lower.append(word)
You can use List Comprehensions to get all upper case characters and lower case characters.
def get_all_cap_lowercase_list(inputStr):
cap_temp_list = [c for c in inputStr if c.isupper()]
low_temp_list = [c for c in inputStr if c.islower()]
print("List of Cap {0} and List of Lower {1}".format(cap_temp_list,low_temp_list))
upper_case_count = len(cap_temp_list)
lower_case_count = len(low_temp_list)
print("Count of Cap {0} and Count of Lower {1}".format(upper_case_count,lower_case_count))
get_all_cap_lowercase_list("Hi This is demo Python program")
And The output is:
List of Cap ['H', 'T', 'P'] and List of Lower ['i', 'h', 'i', 's',
'i', 's', 'd', 'e', 'm', 'o', 'y', 't', 'h', 'o', 'n', 'p', 'r', 'o',
'g', 'r', 'a', 'm']
Count of Cap 3 and Count of Lower 22
Try doing the following:
Split the string into a list where each item is a separate word.
For every word in that list, iterate through and check for capital letters (consider the string constants such as string.uppercase). If it has a capital letter, insert it onto the front of your result list. If not, append it to the end of your result list.
Iterate through your results, printing them. Or, if you want to avoid iterating, join the items in the string using the newline character \n.
Thank you to everyone for your input and help, it was all very informative. Here is the answer that I finally submitted.
s = input("Please enter a sentence: ")
withcap = []
without = []
for word in s.split():
if word.islower():
without.append(word)
else:
withcap.append(word)
onelist = withcap + without
for word in onelist:
print (word)
I think your answer might only be searching for words where the first letter is capitalized. To find words that contain a capital letter anywhere in the word, you'd have to enumerate over each letter in the word, like this:
uin = input("Enter your text: ")
##create lists to hold upper and lower case words
up_words = []
no_up_words = []
for i, word in enumerate(uin.strip().split()):
if word.islower():
no_up_words.append(word)
else:
up_words.append(word)
print(up_words, no_up_words)
My regex:
vendor = "MyNameIsJoe. IWorkInDDFinc."
ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor)
I need split word that would have happened:
My Name Is Joe. I Work In DDF inc.