# 문자열 대소문자 변환 
s="King Dom" 

import string 
print(s.title())                    ## 문장의 첫글자만 대문자로 
print(s.capitalize())             ## 단어별 첫글자를 대문자로 
print(string.capwords(s))      ## split 한 후 단어별 첫글자를 대문자로 변경후 join 

 



# 알파벳/숫자 구별 

string.upper()       → 대문자로 변환

string.lower()       → 소문자로 변환

string.swapcase()  → 대문자 ▷ 소문자, 대문자 ▷ 소문자로 변환

string.capitalize()  → 첫문자를 대문자로 변환

string.title()         → 단어의 첫문자를 대문자로 변환

 

string.isalpha()    --> true/false

 

 

## 문자열 분리 
>>> b = a.split() 
>>> b 
['True', 'love', 'is', 'hard', 'to', 'find', 'now'] 



# 문자열 합치기  
>>> ''.join(b) 
'Trueloveishardtofindnow' 
>>> ' '.join(b) 
'True love is hard to find now' 

 

 


## 문자열 치환
import re
text = u'010-1566#7152'
parse = re.sub('[-=.#/?:$}]', '', text)
print parse


 

# List 생성  
>>> a = "True love is hard to find now" 
>>> a.split() 
['True', 'love', 'is', 'hard', 'to', 'find', 'now'] 

#List 길이 구하기  
>>> len(b) 
7
 
# List 마지막 항목 출력  
>>> b[-1] 
'now' 

 

 


# 숫자, 문자 혼합된 리스트에서 문자열 제거 
    for txt in inList :
        try :
            newList.append(int(txt))
        except :
            continue

 



## 집합 ↔ 리스트 
>>> a=[1,1,2,2,3,3,4,4,5,5]
>>> b=set(a)
>>> b
{1, 2, 3, 4, 5}

>>> c=list(b)
>>> c
[1, 2, 3, 4, 5]



## 딕셔너리 
student={"이름":"로바이"}
student["나이"]=30
list(student.keys())
["이름","나이"]

list(student.values())
["로바이",30]
 


## List 정렬 
>>> a=[1,3,4,5,2]
>>> a.sort()
>>> a
[1,2,3,4,5]

>>> a.reverse()
[5,4,3,2,1]

>>> a[::-1]
[5, 4, 3, 2, 1]



## List 정렬2 (2개 리스트를 한개의 순서에 맞추어 동시에 정렬)
for i in range (0, len(totalID)-1) :
     for k in range(i+1, len(totalID)) :
         if int(totalPay[i]) < int(totalPay[k]) :
             totalPay[i], totalPay[k] = totalPay[k], totalPay[i]
             totalID[i], totalID[k] = totalID[k], totalID[i]

 


## List append 
retList.append([totalID[0], totalPay[0], grade])

## List index 
    for i in range(0,len(userID)) :
        uid = userID[i]
        upay = userPay[i]
        if uid in totalID :
            idx = totalID.index(uid)
            totalPay[idx] += upay
        else :
            totalID.append(uid)
            totalPay.append(upay)



## dictionary 정렬 
import operator
trainlist = sorted(dic.items(), key=operator.itemgetter(1), reverse=True) 
  
  
 
## 변환
숫자를 문자로(ASCii code → 문자) :  chr()
문자를 숫자로(문자 → ASCii code) : ord()

chr(ord(tmp1) +1)

 

 

[Python 문자열 함수 정리]

https://simplesolace.tistory.com/entry/%ED%8C%8C%EC%9D%B4%EC%8D%AC-python-%EB%AC%B8%EC%9E%90%EC%97%B4

 

 

[파이썬] python 문자열 함수정리

이 문서는 파이썬 2점대를 기준으로 작성되었습니다. 4장 문자열 [문자열 대치 기능] >>>import string t = string.Template('$page: $title') t.substitute({'page':2, 'title' : 'The Best of Times'}) t.safe_s..

simplesolace.tistory.com

 

+ Recent posts