首页 > 解决方案 > 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])

标签: pythonstringinputcharacterslice

解决方案


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)

推荐阅读