问题
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])
回答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)
回答2:
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
回答3:
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']
来源:https://stackoverflow.com/questions/60541682/how-to-read-two-characters-from-an-input-string