从python中的字符串中提取每个替代字母的程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20847205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
program to extract every alternate letters from a string in python?
提问by eagertoLearn
Python programs are often short and concise and what usually requires bunch of lines in other programming languages (that I know of) can be accomplished in a line or two in python. One such program I am trying to write was to extract every other letters from a string. I have this working code, but wondering if any other concise way is possible?
Python 程序通常简短而简洁,在其他编程语言(我知道的)中通常需要大量行的内容可以在 Python 中用一两行来完成。我正在尝试编写的一个这样的程序是从字符串中提取所有其他字母。我有这个工作代码,但想知道是否有其他简洁的方式可能?
>>> s
'abcdefg'
>>> b = ""
>>> for i in range(len(s)):
... if (i%2)==0:
... b+=s[i]
...
>>> b
'aceg'
>>>
采纳答案by Maciej Gol
>>> 'abcdefg'[::2]
'aceg'
回答by Maciej Gol
Use Explain Python's slice notation:
>>> 'abcdefg'[::2]
'aceg'
>>>
The format for slice notation is [start:stop:step]. So, [::2]is telling Python to step through the string by 2's (which will return every other character).
切片符号的格式是[start:stop:step]. 因此,[::2]是告诉 Python 以 2 为单位逐步遍历字符串(这将返回每隔一个字符)。
回答by brain storm
you could try using slice and join:
您可以尝试使用切片并加入:
>>> k = list(s)
>>> "".join(k[::2])
'aceg'
回答by rlms
Practically, slicing is the best way to go. However, there are also ways you could improve your existing code, not by making it shorter, but by making it more Pythonic:
实际上,切片是最好的方法。但是,还有一些方法可以改进现有代码,不是通过缩短代码,而是通过使其更具 Python 风格:
>>> s
'abcdefg'
>>> b = []
>>> for index, value in enumerate(s):
if index % 2 == 0:
b.append(value)
>>> b = "".join(b)
or even better:
甚至更好:
>>> b = "".join(value for index, value in enumerate(s) if index % 2 == 0)
This can be easily extended to more complicated conditions:
这可以很容易地扩展到更复杂的条件:
>>> b = "".join(value for index, value in enumerate(s) if index % 2 == index % 3 == 0)
回答by abarnert
The rightway to do this is to just slice the string, as in the other answers.
在正确的做到这一点的方法是只切串,如在其他的答案。
But if you want a more concise way to write yourcode, which will work for similar problems that aren't as simple as slicing, there are two tricks: comprehensions, and the enumeratefunction.
但是如果你想要一种更简洁的方式来编写你的代码,这将适用于不像切片那么简单的类似问题,有两个技巧:理解和enumerate函数。
First, this loop:
首先,这个循环:
for i in range(len(foo)):
value = foo[i]
something with value and i
… can be written as:
……可以写成:
for i, value in enumerate(foo):
something with value and i
So, in your case:
所以,在你的情况下:
for i, c in enumerate(s):
if (i%2)==0:
b+=c
Next, any loop that starts with an empty object, goes through an iterable (string, list, iterator, etc.), and puts values into a new iterable, possibly running the values through an iffilter or an expression that transforms them, can be turned into a comprehension very easily.
接下来,任何以空对象开始、经过可迭代对象(字符串、列表、迭代器等)并将值放入新可迭代对象(可能通过if过滤器或转换它们的表达式运行值)的循环都可以是很容易就变成了领悟。
While Python has comprehensions for lists, sets, dicts, and iterators, it doesn't have comprehensions for strings—but str.joinsolves that.
虽然 Python 具有对列表、集合、字典和迭代器的理解,但它没有对字符串的理解——但str.join解决了这个问题。
So, putting it together:
所以,把它放在一起:
b = "".join(c for i, c in enumerate(s) if i%2 == 0)
Not nearly as concise or readable as b = s[::2]… but a lot better than what you started with—and the same idea works when you want to do more complicated things, like if i%2 and i%3(which doesn't map to any obvious slice), or doubling each letter with c*2(which could be done by zipping together two slices, but that's not immediately obvious), etc.
不像b = s[::2]……那么简洁或易读,但比你开始的要好得多——当你想做更复杂的事情时,同样的想法也行得通,比如if i%2 and i%3(不映射到任何明显的切片),或者将每个字母加倍c*2(这可以通过将两片压缩在一起来完成,但这不是很明显)等。
回答by Stryker
Here is another example both for list and string:
这是列表和字符串的另一个示例:
sentence = "The quick brown fox jumped over the lazy dog."
sentence[::2]
Here we are saying: Take the entire string from the beginning to the end and return every 2nd character.
我们在这里说:从头到尾取整个字符串并返回每第二个字符。
Would return the following:
将返回以下内容:
'Teqikbonfxjme vrtelz o.'
You can do the same for a list:
您可以对列表执行相同的操作:
colors = ["red", "organge", "yellow","green", "blue"]
colors[1:4]
would retrun:
会重新运行:
['organge', 'yellow', 'green']
The way I read the slice is: If we have sentence[1:4]Start at index 1 (remember the starting position is index 0) and Stop BEFORE the index 4
我读取切片的方式是:如果我们sentence[1:4]从索引 1 开始(记住起始位置是索引 0)并在索引 4 之前停止

