Startup Data scientist Blog

データ分析系のテック情報を発信します

python stringsとnumberの基本的なコード

数字型

#number
age = 99
pi = 3.14
print(age)
print(pi)

Output

>>

99
3.14

 

文字列

#strings
s = 'Rutherford Birchard Hayas'
tokens = s.split()
firstName = tokens[0]
middleName = tokens[1]
lastName = tokens[2]
s2 = firstName + " " + middleName + " " + lastName

print(s)
print(tokens)
print(firstName)
print(middleName)
print(lastName)
print(s2)

Output

>>

Rutherford Birchard Hayas
['Rutherford', 'Birchard', 'Hayas']
Rutherford
Birchard
Hayas
Rutherford Birchard Hayas

 

s = 'Rutherford Birchard Hayas'
tokens = s.split()
firstName = tokens[0]
middleName = tokens[1]
lastName = tokens[2]
s2 = firstName + " " + middleName + " " + lastName

if s == s2:
    print("yes!")
else:
    print("No!")

Output

>>

yes!

 

リストとfor

#list
beatles = ['John', 'Paul', 'George']
beatles.append('Ringo')

for b in beatles:
    print('Hello' + b)

Output

>>

HelloJohn
HelloPaul
HelloGeorge
HelloRingo

 

How to sort

#tuple
ages = (18, 21,28, 21, 22, 18, 19, 34, 9)

#set
uniqueAges = set(ages)
uniqueAges.add(18)     #既に18は入っているので意味がはない
uniqueAges.remove(21)  #21が取り除かれる

for thisAge in uniqueAges:
    print(thisAge)
   
if 18 in uniqueAges:
    print('This is 18years old present!')
   
orderedUniqueAges = sorted(uniqueAges)
print(orderedUniqueAges)

Output

>>

34
9
18
19
22
28
This is 18years old present!
[9, 18, 19, 22, 28, 34]

docs.python.org

 

pythonの辞書形式

#dict 辞書形式
netWorth = {}
netWorth['Donald Trump'] = 3000000000
netWorth['Bill Gates'] = 58000000000
netWorth['Tom Cruise'] = 40000000
netWorth['Joe Postdoc'] = 20000

for (person, worth) in netWorth.items():
    if worth < 1000000:
        print(person + 'is not a millionaire')
       
       
if 'Tom Cruise' in netWorth:
    print('Show me the money!')

Output

>>

Joe Postdocis not a millionaire
Show me the money!