簡體   English   中英

Python 字符串格式化

[英]Python strings formatting

給定一個至少包含一個空格字符的字符串。 輸出位於源字符串的第一個和第二個空格之間的子字符串。 如果字符串只包含一個空格,則輸出一個空字符串。 我的嘗試:但是輸入不正確,例如: 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")

示例:1

假設輸入如下:

hello my name is abc

輸出應該是

hello my

示例 2:

輸入

hello my

輸出

None

代碼:

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

這里是

    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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM