Basic Python

sep, end=, replace, upper, lower, isupper, islower, capitalize, insert, join, *(star expression), partition

Naranjito 2021. 5. 8. 18:13
  • sep

Seperator, between the arguments to print() function.

print('naver','kakao','samsung',sep=';')
>>>
naver;kakao;samsung

print('naver','kakao','sk','samsung',sep='/')
>>>
naver/kakao/sk/samsung

 

  • end=

It can be put anything in end, then it will be following. '\n\ is the default.

print("first",end=' ');print("second")
>>>
first second

; : Multiple command in one line.

 

  • replace

string.replace(old,new) : Replace the string from old to new.

phone_number = "010-1111-2222"
phone_number=phone_number.replace('-',' ')
print(phone_number)
>>>
010 1111 2222

As JSON only allows enclosing strings with double quotes you can manipulate the string like this

import json
v2_dict=list(map(lambda n:json.loads(n.replace("\'", "\"")),RISK_V2))

 

  • upper

It converts all lowercase characters in a string into uppercase characters and returns it.

ticker = "btc_krw"
ticker.upper()
>>>
'BTC_KRW'

 

  • lower
ticker = "BTC_KRW"
ticker.lower()
>>>
'btc_krw'

 

  • isupper

It returns true if all the characters are in upper case. The opposite is islower().

 

li = ["A", "b", "c", "D"]
for i in li:
    if i.isupper():
        print(i)
>>>
A
D

 

  • capitalize

It converts the first character of the string to a capital(uppercase) letter while making all other characters in the string lowercase letters.

ticker = "hello"
ticker.capitalize()
>>>
'Hello'

 

  • insert

insert(index, item) : Inserts an item at the specified index.

movie_rank.insert(1,'슈퍼맨')
movie_rank
>>>
['닥터 스트레인지', '슈퍼맨', '스플릿', '럭키', '배트맨']

 

  • extend

It adds all the elements of an iterable to the end of the list.

 

a=[1,2,3]
a.extend([4,5,6])
a
>>>
[1, 2, 3, 4, 5, 6]

 

  • extend vs append

 

  • join

It takes all items in an iterable and joins them into one string.

interest = ['삼성전자', 'LG전자', 'Naver', 'SK하이닉스', '미래에셋대우']
' '.join(interest)
>>>
'삼성전자 LG전자 Naver SK하이닉스 미래에셋대우'

 

  • partition

It searches for a specified string and splits the string into a tuple containing three elements.

first element second element thrid element
                                   ⇡
                        specified string
x="I could eat bananas all day".partition('bananas')
x
>>>
('I could eat ', 'bananas', ' all day')

 

  • *(star expression)

In tuple, * allowing to specify a "catch-all" which will be assigned a list of all items not assigned to a "regular" name.

scores = [8.8, 8.9, 8.7, 9.2, 9.3, 9.7, 9.9, 9.5, 7.8, 9.4]
*a,b,c=scores 
a
>>>
[8.8, 8.9, 8.7, 9.2, 9.3, 9.7, 9.9, 9.5]