简体   繁体   English

从index [0]到随机索引,对字符串列表进行切片

[英]slice a list of strings from index[0] till random index

I am trying to slice a list of strings from index[0] till a random index. 我试图切片从索引[0]到随机索引的字符串列表。 The index number where the slicing needs to end, is always at the index number that holds a "(". The code i'm trying is as follow 切片需要结束的索引号始终位于包含“(”的索引号。我尝试的代码如下

new_name = [[:x:] if x == "(" else x for x in new_name]

I always get invalid syntax error. 我总是收到无效的语法错误。 How can i make this work? 我该如何工作?

thx in advance 提前

The x variable in the for expression is assigned to each character in new_name for each iteration, not the index of each character. 对于每次迭代,将for表达式中的x变量分配给new_name中的每个字符,而不是每个字符的索引。

For your purpose you should simply use the str.find() method to get the index of a given character in a string: 为了您的目的,您应该只使用str.find()方法来获取字符串中给定字符的索引:

new_name = new_name[:new_name.find('(')]

List Comprehension method: 列表理解方法:

l = list('sandeep(Kadapa)')

[i for i in iter(lambda x=iter(l): next(x),'(')]

['s', 'a', 'n', 'd', 'e', 'e', 'p']

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

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