[英]Slicing string object in Array
def shorten_string(arr):
newchar = []
for char in arr:
#for z in char:
if char[-2:] == "Ja":
newchar = char[0:-2]
elif char[-4:] == "Nein":
newchar = char[0:-4]
newchar.append(char)
return newchar
Reading an array with strings like:读取包含以下字符串的数组:
arr = ["KK_abc_Nein","KK_abc_Ja","KK_def_Nein","KK_def_Ja"]
I would like to find out if the last letters match with the string object and then append the String without _Nein or _Ja to the array and return it.我想找出最后一个字母是否与字符串对象匹配,然后将没有_Nein或_Ja的字符串附加到数组中并返回它。
'str' object has no attribute 'append'
most of the time i receive this error.大多数时候我都会收到这个错误。
Basically you are currently overwriting the newchar
list by assigning a string to it.基本上,您当前正在通过newchar
分配一个字符串来覆盖newchar
列表。
Instead you can use split()
, pop()
and join()
to do the work:相反,您可以使用split()
、 pop()
和join()
来完成这项工作:
def shorten_string(arr):
known_ends = ["Ja", "Nein"]
newchar = []
for char in arr:
char = char.split("_")
end = char.pop()
if end in known_ends:
newchar.append("_".join(char))
return newchar
This will work with any number of "words"这将适用于任意数量的“单词”
>>> arr = ["KK_abc_Nein","KK_abc_Ja","KK_def_Nein","KK_def_Ja"]
>>> shorten_string(arr)
>>> ['KK_abc', 'KK_abc', 'KK_def', 'KK_def']
EDIT: Added list known_ends
to easily update the list of ends you want to process instead of overloading the if
statement编辑:添加了列表known_ends
以轻松更新要处理的结束列表,而不是重载if
语句
对于此示例,您可以简单地执行以下操作:
arr = [x.replace('_Nein','').replace('_Ja','') for x in arr]
what about:关于什么:
arr = ["KK_abc_Nein","KK_abc_Ja","KK_def_Nein","KK_def_Ja"]
b = [ s.replace('_Nein', '').replace('_Ja', '') for s in arr]
print(b)
will output会输出
['KK_abc', 'KK_abc', 'KK_def', 'KK_def']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.