Hack-file

ハッキングに関してまとめるブログ。高校生がハッカーを目指している。たまに哲学、都市伝説

【基礎】Python文字列 ざっくり解説。他の言語やってる人はすんなり入ると思う

f:id:umituki_pc:20190118002122p:plain

 

# helloworldを出してみる
print("hello,world")

 

実行結果

hello,world

 

printの中の文字が表示される。

このときに必ず "  や ' などで囲うようにする。

#改行の場合
test = """moji
moji"""
print(test)
#文字をくっつけることも可能
test2 = 'hello'
test2 = test2 + '!'
test2 = test2 + '!'
print(test2)
test3 = '123'
test3 += '456'
test3 += '789'
print(test3)

 

実行結果

 moji
moji
hello!!
123456789
123123123

mojiはちゃんと改行されているのがわかる。

helloにもちゃんと!!が2つついているのがわかる。

数字もくっつけることができた。

#文字を繰り返し表示
test4 = '123' * 3
print(test4) 

実行結果

123123123

 

となる。文字列をこれで繰り返すことが可能になった。 

#数字を文字にする
test5 = 1007

print(str(test5) + '万') 

実行結果

1007万

 

print(test5 + '万')

だとエラーが生じるはず。 

#入れ替え
test6 = 'pythem'

print(test6.replace('em','on'))

 

test6の変数の中に、pythonの綴が間違ってしまっているので直す。

 

実行結果

python

 

うまく表示できた。

 

print(変数名.replace('置き換えたい文字','置き換える文字')

 

で、できる。 

#文字を分ける
test7 = "py-thon"
print(test7.split('-'))
 

 文字を分けることができる。

 

実行結果

['py', 'thon']

 

print(変数名.split('分けたい場所')) 

で、できる

 

#文字列の桁揃え
test8 = '1234'

print(test8.rjust(10,'!'))

print(test8.zfill(10))
print(test8.zfill(3))

実行結果

!!!!!!1234
0000001234
1234

 !マークが十桁になるように割り当てられた。

また、zfillにより、0を指定した桁分割り当てることができた。

# 文字検索、先頭が任意の文字か

print(test7.startswith('py'))
print(test7.startswith('thon'))

 

実行結果 

True
False

となる

 

 

# 文字が含まれているか?

test7 = "py-thon"

print('p' in test7)

print('j' in test7)

 

実行結果 

True
False

となる

 


# 大文字小文字変換
test0 = 'hack-file'

print(test0.upper())
print(test0.lower())

 

 upperで大文字。lowerで大文字になる。

 

メモ程度