[英]Python strings formatting
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=Hello World 我的名字,输入是: World my ,我不知道为什么,你能帮帮我吗?
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")
Example: 1示例:1
Assuming the input like:假设输入如下:
hello my name is abc
Output should be输出应该是
hello my
Example 2:示例 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
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.