python文本 單獨(dú)處理每個(gè)字符的方法匯總

2022-07-04 15:13 更新

python 文本 單獨(dú)處理字符串每個(gè)字符的方法匯總

場(chǎng)景:

用每次處理一個(gè)字符的方式處理字符串

方法:

1. 使用 list(str)

  >>> a='abcdefg'  
  >>> list(a)  
  ['a''b''c''d''e''f''g']  
  >>> aList=list(a)  
  >>> for item in aList:  
      print(item)#這里可以加入其他的操作,我們這里只是單純使用print  
    
        
  a  
  b  
  c  
  d  
  e  
  f  
  g  
  >>>   

2. 使用 for 遍歷字符串


  >>> a='abcdefg'  
  >>> for item in a :  
      print(item)#這里可以加入其他的操作,我們這里只是單純使用print  
    
        
  a  
  b  
  c  
  d  
  e  
  f  
  g  
  >>>   

3. 使用 for 解析字符串到 list 里面

  >>> a='abcdefg'  
  >>> result=[item for item in a]  
  >>> result  
  ['a''b''c''d''e''f''g']  
  >>>   
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)