簡體   English   中英

使用字符和字符數打印自定義字符串,而無需使用python內置方法

[英]Print custom string with character and character count without using python built-in methods

我想調整字符串以打印字符和字符數,而無需使用python內置方法。

>>> string = 'aaaabbbddd'

我正在尋找此輸出:

a4b3d3

這是一種無需內置方法即可完成的方法!

def count_modify(string):
    d = {}
    for i in string:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return ''.join(str(x)+str(d[x]) for x in d)

另外,您可以決定不使用join()方法,而是執行以下操作

def count_modify(string):
        d = {}
        for i in string:
            if i in d:
                d[i] += 1
            else:
                d[i] = 1
        n_str = ''
        for i in d:
            n_str += str(i)+str(d[i])
        return n_str

現在唯一使用的明顯方法是str()方法!

這可能看起來有點長,但我希望這能解決您的問題

string='aaaabbbddd'    
elems=set(string)
result=''
for ele in elems:
    result = result+ele+str(string.count(ele))

希望能幫助到你。 快樂編碼:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM