Given a string containing at least one space character. Output the substring located between the first and second spaces of the source string. If the string contains only one space, then output an empty string. My attempt: But input is incorrect, for example: user_input=Hello World my name , input is: World my , i don't know why , can you help me?
user_input = input("Enter your string: ")
space_counter = 0
for char in user_input:
if char == " ":
space_counter = 1
if space_counter > 1:
start_space_index = None
for i in range(len(user_input)):
if user_input[i] == " ":
start_space_index = i
break
second_space_index = None
for i in range(len(user_input)-1, -1, -1):
if user_input[i] == " ":
second_space_index = i
break
print(user_input[start_space_index 1: second_space_index])
else:
print("Empty string")
CodePudding user response:
Example: 1
Assuming the input like:
hello my name is abc
Output should be
hello my
Example 2:
input
hello my
output
None
Code:
a = 'hello my name is abc'
obj = a.split(" ") #this splits like ['hello', 'my', 'name', 'is', 'abc']
if len(obj) > 2:
print(obj[0], obj[1])
else:
print None
CodePudding user response:
Here, it is
user_input = input("Enter your string: ")
Lst = user_input.split(" ")
space_counter = 0
for char in user_input:
if char == " ":
space_counter = 1
if space_counter > 1:
start_space_index = None
for i in range(len(user_input)):
if user_input[i] == " ":
start_space_index = i
break
second_space_index = None
for i in range(len(user_input)-1, -1, -1):
if user_input[i] == " ":
second_space_index = i
break
if user_input[0] == " ":
print(Lst[0])
else:
print(Lst[1])