python - 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.
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)
推荐阅读
- xsd - 将多个 XSD 文件转换为 AVRO 架构
- python - 为什么 Python 中的原子分组比简单的非捕获交替慢?
- liferay - 我无法在 Web 内容中选择类别。(Liferay 7.4.2)
- haskell - 如何从 Haskell 中的字符串中删除某个字符?
- kotlin - Kotlin rotateAnimation 不起作用。单击 spinBtn 时没有任何反应
- git - 无法从 git 中取消暂存文件
- mysql - 无法连接到 localhost (0) 上的 mysql 服务器
- python - 在单行中设置 pyplot 属性
- python - Python中的并行处理efficient_apriori代码
- javascript - 将数据从客户端(vanilla js)发送到 .net 核心 API