【问题标题】:Understanding how to use Indexing了解如何使用索引
【发布时间】:2016-11-18 12:26:50
【问题描述】:

寻找关于如何实现以下说明的更好说明。

# loop while i is less than the length of name and the i-th character is not a space.
# return the part of name up to but not including the i-th character to the caller.
def get_first_name(name):
    i = 0
    while i < len(name) and '' in str(i):
        i += 1
    return name 

【问题讨论】:

  • “第i个字符”是索引i处的字符,即name[i]。请注意,通常不需要按索引迭代 Python 字符串 - 您可以改为使用 for char in name: 来获取每个字符。

标签: python indexing


【解决方案1】:

我没有实现你的功能,只是解释逻辑,因为我相信这是你练习的一部分。

你的条件可以写成:

name = "Hello World"
i = 0

# len(name): will return the length of `name` string
# name[i] != " ": will check that item at `i`th position is not blank space

while i < len(name) and name[i] != " ":
    print name[:i+1]  # print string from start to the `i`th position
    i += 1

将打印:

H
He
Hel
Hell
Hello

现在,我猜你知道如何将这个逻辑放在你的函数中,以及返回哪个值;)

【讨论】:

  • 感谢您的建议,它帮助我更好地理解了问题。
  • 我很高兴知道我帮助提出问题的人更好地了解他的问题。开个玩笑:D我知道你的意思是你的任务;)
【解决方案2】:

Python 中的字符串是序列,您可以使用name[i] 之类的符号对其进行索引。因此,您可以逐字母遍历字符串,并继续与空格字符' ' 进行比较。每次您击中一个不是空格的字母时,将其附加到您的临时字符串中。一旦你点击一个空格,停止循环,你的临时字符串的值将代表他们的名字。

def get_first_name(name):
    first = ''
    i = 0
    while i < len(name) and name[i] != ' ':
        first += name[i]  # append this letter
        i += 1            # increment the index
    return first

例子

>>> get_first_name('John Jones')
'John'

【讨论】:

    【解决方案3】:

    感谢您的建议,使用它们我已经能够让我的代码按照我需要的规范工作。

       # Function designed to retrieve first name only from fullname entry.
    def get_first_name(name):
        i = 0 
        while i < len(name) and name[i] !=" ":
            i += 1
        return name[:i]
    
    # Function designed to retrieve first initial of last name or first initial of first name if only one name input.
    def get_last_initial(name):
        j = len(name) - 1 
        while j >= 0 and name[j] !=" ":
            j-=1
        return full_name[j+1]
    
    # Function that generates username based upon user input.
    def get_username(full_name):
        username = get_first_name(full_name) + get_last_initial(full_name) 
        return username.lower()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-24
      • 2016-01-03
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      相关资源
      最近更新 更多