0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

1/30 days hackerrank で学んだこと。

Posted at

この記事は、
pythonを用いてHackerRank1/30に取り組んだ時に、
調べた内容をまとめたものです。

データ型~数値の扱い~

int:整数を扱う
double:有効桁数15桁
float:有効桁数6,7桁
string:文字列型の扱い
round:四捨五入

データ型の変換を__キャスト__という。
printで数値を出力するときにstrをよく忘れるので注意です。

listで文字列を1文字ずつ認識できる

例)

str="Hacker"
char_list=list(str)
print(char_list)

で、["H", "a", "c", "k", "e", "r"]と出力されます。

リストを文字列に変換する

つまり今度は、
["H", "a", "c", "k", "e", "r"]
と表示されるものを、

Hacker
直したいということです。

①forをつかう

str_list = ['python', 'list', 'exchange'] 
 mojiretu = ' ' 
for x in str_list:
mojiretu += x
print(mojiretu) 

実行結果:pythonlistexchange

②joinを使う
join関数の使い方
文字列 = ‘区切り文字’.join(リスト)

str_list = ['python', 'list', 'exchange']
mojiretu = ','.join(str_list) 
print(mojiretu)

実行結果:python,list,exchange

スライス

列の要素を部分的に取り出すのに有用な方法です。

基本の例)
@ycctw1443さんのものを引用しています。

a = [1, 2, 3, 4, 5]
print(a[0: 4])
print(a[: 4])
print(a[-3:])
print(a[2: -1])

すると、
[1, 2, 3, 4]
[1, 2, 3, 4]
[3, 4, 5]
[3, 4]
と出力されます。

これを発展させ、
「n番目ごとに要素を得る」こともできます。
a[始まりの位置: 終わりの位置: スライスの増分]です。

a = [1, 2, 3, 4, 5]
print(a[:: 2])
print(a[1:: 2])
print(a[::-1])
print(a[1::-1])

結果)
[1, 3, 5]
[2, 4]
[5, 4, 3, 2, 1]
[2, 1]

複数の文字列を入力する

input().split()

printと%

%を使えば、変数が組み込まれた文字列を
簡潔に出力することができます。

print("好きな果物は、%sです。" %'リンゴ') 
print("好きな果物は、%sと%sです。" %('リンゴ','ミカン')) 

x = 'サッカー' 
y = 'スノーボード' 
print("好きなスポーツは、%sと%sです。"%(x,y)) 

%sはstr()をあらわし、
値を文字列として整数も少数も表示できますが、
%dとすると整数になります。

%rはrepr()で、
渡された値をそのまま表示します。

Star演算子

配列を展開することができます。

参考

https://programming-study.com/technology/python-list-join/
https://code-graffiti.com/print-format-with-string-in-python/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?