简体   繁体   English

在Python中获取字符串中的第n个字符

[英]Getting every nth character in the string in Python

I have the following function but it doesn't give me the intended result: 我具有以下功能,但未达到预期的效果:

def GetNthLetters(text,n):
    builtstring=""
    for letter in text:
        if text.index(letter)%n==0:
            builtstring=builtstring+letter
            print letter 
    return builtstring   

str.index() finds the first match for your letter. str.index()查找字母的第一个匹配项 If you have a letter that appears more than once, that'll give you the wrong index. 如果您的信件出现多次,那将给您错误的索引。 For any given character, you only test if their first occurrence in the string is at a n'th position. 对于任何给定字符,您仅测试它们在字符串中的第一次出现是否在 n个位置。

To demonstrate, take a look at the string 'hello world' with the character indices (I used . to mark the space): 为了演示,请看一下带有字符索引的字符串'hello world' (我用.来标记空格):

0 1 2 3 4 5 6 7 8 9 10
h e l l o . w o r l d

For the letter l , text.index('l') will return 2 , so it'll only be included in the output if n is 1 or 2 . 对于字母ltext.index('l')将返回2 ,因此仅当n12时才将其包含在输出中。 It doesn't matter that l also appears at index 3 or 9, because you only ever test 2 % n == 0 . l也出现在索引3或9上都没关系,因为您只测试过2 % n == 0 The same applies for 'o' (positions 4 and 7), only 4 % n == 0 is tested for either. 'o' (位置4和7)也是如此,其中只有4 % n == 0才被测试。

You could use the enumerate() function to give you a running index: 您可以使用enumerate()函数为您提供运行索引:

def GetNthLetters(text, n):
    builtstring = ""
    for index, letter in enumerate(text):
        if index % n == 0:
            builtstring = builtstring + letter
    return builtstring

Now index is correct for every letter, repeated or not. 现在index对于每个字母都是正确的,无论是否重复。

However, it'll be much easier to use slicing: 但是,使用切片会容易得多:

def GetNthLetters(text, n):
    return text[::n]

This takes every n'th letter too: 这也需要第n个字母:

>>> 'foo bar baz'[::2]
'fobrbz'
>>> 'foo bar baz'[::3]
'f ra'
>>> 'foo bar baz'[::4]
'fbb'

If somebody asked me to give every nth character in a string, I wouldn't include the first character. 如果有人要求我在字符串中输入第n个字符,则不会包含第一个字符。 I would rather do something like below: 我宁愿做如下事情:

def GetNthLetters(text, n):
    builtstring = ""
    for i in range(0, len(text)):
        if (i + 1) % n == 0:
            # print(text[i])
            builtstring = builtstring + text[i]
    return builtstring


text = '1234567890123456789012345678901234567890'

nthLetters = GetNthLetters(text, 1)
print(nthLetters)
nthLetters = GetNthLetters(text, 2)
print(nthLetters)
nthLetters = GetNthLetters(text, 3)
print(nthLetters)
nthLetters = GetNthLetters(text, 10)
print(nthLetters)
nthLetters = GetNthLetters(text, 40)
print(nthLetters)

This would yield these results: 这将产生以下结果:

1234567890123456789012345678901234567890 1234567890123456789012345678901234567890

24680246802468024680 24680246802468024680

3692581470369 3692581470369

0000 0000

0 0

string = "12345678"

n = 2

splitted_string = string[::n]

print(splitted_string)

# Output : 1357

Hope this will help.! 希望这会有所帮助。

Using Python's slicing syntax: 使用Python的slicing语法:

Python's slicing syntax is much like the range() function. Python的slicing语法非常类似于range()函数。 It accepts a start , stop and step value: 它接受一个startstopstep值:

string[start : stop : step]

where you can leave any of the parameters blank and they will default to 0 , the length of the string and 1 respectively. 您可以在其中保留任何参数为空白,它们的默认值分别为0 ,字符串的长度和1

This means you can do: 这意味着您可以:

string[::n ] string[::n ]

to get a string's every nth characterter. 获取字符串的nth字符。

So you can write the function as: 因此,您可以将function编写为:

def getNthLetters(text, n):
   return text[::n]

Hope this does what you want! 希望这能满足您的需求!

The problem with the code is everytime the index of same repeated letter will give same result. 代码的问题是每次相同重复字母的索引都会得到相同结果。

For example 'Hello World!'.index('o') will be always 4 so it will not give intended result. 例如,“ Hello World!”。index('o')始终为4,因此不会给出预期的结果。

The best way is to enumerate the for loop. 最好的方法是enumerate for循环。 so you will get appropriate index. 这样您将获得适当的索引。

You should also remember array starts with 0 not 1. 您还应该记住,数组以0而不是1开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM