简体   繁体   English

获取 Python 中字符串的每第二个和第三个字符

[英]Get every 2nd and 3rd characters of a string in Python

I know that my_str[1::3] gets me every 2nd character in chunks of 3, but what if I want to get every 2nd and 3rd character?我知道my_str[1::3]以 3 个块的形式获取每个第二个字符,但是如果我想获取每个第二个和第三个字符怎么办? Is there a neat way to do that with slicing, or do I need some other method like a list comprehension plus a join:有没有一种巧妙的方法可以通过切片来做到这一点,或者我是否需要一些其他方法,比如列表理解和连接:

new_str = ''.join([s[i * 3 + 1: i * 3 + 3] for i in range(len(s) // 3)])

I think using a list comprehension with enumerate would be the cleanest.我认为使用带有enumerate的列表理解将是最干净的。

>>> "".join(c if i % 3 in (1,2) else "" for (i, c) in enumerate("peasoup booze scaffold john"))
'eaou boz safol jhn'

Instead of getting only 2nd and 3rd characters, why not filter out the 1st items?为什么不过滤掉第一个项目,而不是只得到第二个和第三个字符?

Something like this:像这样的东西:

>>> str = '123456789'
>>> tmp = list(str)
>>> del tmp[::3]
>>> new_str = ''.join(tmp)
>>> new_str
'235689'

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

相关问题 Python:如何删除文本文件每一行的第二和第三元素/变量 - Python: How to delete the 2nd and 3rd element/variable for every line of text file 捕获Pandas中第2个和第3个空格之前的所有字符串 - Capture all the string before the 2nd and 3rd whitespace in Pandas Python-按第二个元素然后按第三个元素对嵌套列表进行排序 - Python - Sorting nested list by 2nd element, then by 3rd element 如何从文本文件中切出第二列和第三列? 蟒蛇 - How to cut 2nd and 3rd column out of a textfile? python 在 Python 中查找第 2 和第 3 大值 - Find 2nd and 3rd highest value in Python Python正则表达式匹配行中的第二个或第三个单词 - Python Regex match 2nd or 3rd word in line 如何读取第二行和第三行,然后每五行读取一次:第二,第三,第七,第八,十二,十三等 - How to Read the 2nd and 3rd line then Every Fifth Line After: 2nd, 3rd, 7th, 8th, 12th, 13th, etc 如何使用Flask在列表中设置每个第1,第2,第3个帖子的颜色? - How to set color of every 1st, 2nd, 3rd post in a list with Flask? 每行第一,第二和第三行读取一个txt文件,并保存在3个不同的列表中 - Read a txt file every first, 2nd and 3rd line and save in 3 different lists 将第 2 行和第 3 行移动到第 1 行的末尾 - Move every 2nd and 3rd row to the end of the 1st row
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM