【问题标题】:How Split method and spaces in python helped in changing positions of letters?python中的Split方法和空格如何帮助改变字母的位置?
【发布时间】:2022-08-18 15:18:04
【问题描述】:

所以这里有这段代码,解决方案已经写好了,但我无法理解它。 \'say\' 变量是如何以只有空格和索引的顺序分配文本的。以及上面的拆分方法的作用是什么。尽管我非常了解列表方法,但解决方案对我来说是模糊的。任何澄清? .

问题:

让我们创建一个将文本转换为猪拉丁文的函数:一个简单的文本 修改每个单词的转换,将第一个字符移动到 末尾并在末尾附加“ay”。例如,python 最终为 亿通支付。

编码:

def pig_latin(text):
    say = \"\"
    # Separate the text into words
    words = text.split (\' \')
    for word in words:
        # Create the pig latin word and add it to the list
        say += word[1:]+word[0]+\'ay \'
    # Turn the list back into a phrase
    return say
        
print(pig_latin(\"hello how are you\")) # Should be \"ellohay owhay reaay ouyay\"
print(pig_latin(\"programming in python is fun\")) # Should be \"rogrammingpay niay ythonpay siay unfay\"
  • 请更新代码的缩进。 Python 对缩进非常敏感,python 程序员也是如此。

标签: python indexing split


【解决方案1】:

拆分文档https://docs.python.org/3.3/library/stdtypes.html?highlight=split#str.split

切片文档:https://docs.python.org/3/library/functions.html#slice

a = "String that will be splited using space"
# split methos is used to create list from string,
# in the split we specify 'sep' parameter that is used as delimiter to separate the string
print("Split:", a.split(' '))
b = a.split(' ')
s = ''  # empty string
for i in b:
    # the slice operation in string and list is based on index
    print("Slice:", i[1:], i[0], i[1:]+i[0]+'ay ')
    s += i[1:]+i[0]+'ay '
print("Final string:", s)

【讨论】:

    猜你喜欢
    • 2019-03-30
    • 2010-10-13
    • 2022-01-25
    • 2019-05-08
    • 1970-01-01
    • 2022-01-18
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多