如何从输入字符串中读取两个字符? [英] How to read two characters from an input string?
本文介绍了如何从输入字符串中读取两个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望程序从随机字符串的输入中读取一个字符,但是当字符串中有空格时,我希望它读取接下来的两个字符。
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.
例如,如果我键入 H ,我希望它返回
H
的值,然后检测空格然后返回 He
。我该怎么做?
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)
这篇关于如何从输入字符串中读取两个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文