[英]split python string every nth character (string and nth character are in lists)
[英]Split characters from string by nth character python
我有兩種特殊類型的字符串(均由小寫英文字母組成): two_string:長度為 2 的字符串(例如:“ab”,“zz”)three_string:長度為 3 的字符串(例如:“abc”,“ghw”)
我必須通過在一行中並排放置一個或多個 two_strings 和 three_strings 來創建新字符串,並且不要將兩個相同的字符串並排放置。 從上面的示例中,您可以創建例如“abzz”、“ababc”、“zzabcghwab”等。
情況是,我需要從輸入字符串中生成一個可能的兩個字符和三個字符的列表
例如,
input_string = "abcdef" output = ["ab","abc","cd","def","ef"] 等。
input_string1 = "abcdefg" output1 = ["ab","abc","cd","cde","de","efg"] 等等..
input_string2 = "ababcabc" output2 = ["aba","abc","bc","bca","ab","ca"] 等等。
input_string3 = "ccccacccc" output3 =["cac","ccc"] 等等..
def split_string(strg):
strg_len = len(strg)
output_strg = []
for x in range(0,len(strg)):
x_2 = x+2
x_3 = x+3
two_ltr_com = strg[x:x_2]
if(len(two_ltr_com) > 1):
if(two_ltr_com not in output_strg):
output_strg.append(two_ltr_com)
if(x+3 <= len(strg)):
three_ltr_com = strg[x:x_3]
if(three_ltr_com not in output_strg):
output_strg.append(three_ltr_com)
return output_strg
result = split_string("abcdef")
print(result)
在這種情況下誰能幫助我? 提前致謝
我想我要做的是有一個循環遍歷所需的 substring 長度。 例如,在這種情況下for substr_len in (2, 3):
。
在該循環中,我將使用另一個循環來迭代字符串索引。 我會在一個set
中收集所有匹配的字符串,它會處理重復項(集合不能包含重復項)。
所以作為一個粗略的草圖:
s = "abcdefghij"
substrings = set()
for substring_len in (2, 3):
for idx in range(0, len(s), substring_len):
ss = s[idx:idx+substring_len]
substrings.add(ss)
我認為您需要考慮的唯一另一件事是如何處理長度不能完全除以 12 的輸入字符串 - 例如,“abc”的 2-string[s] 是什么樣的?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.