[Python] 文字列を区切ってみる
こんにちは、@yasuです。
今日は、文字列を区切ってみたいと思います。
- 文字列を位置で区切る
- 文字列を文字で区切る
実行環境はこちらです。
https://repl.it/
文字列を位置で区切る
コード
# 文字列を位置で区切る
# 両側のカッコを取る。
# ゼロおよびプラスなら左からの位置
# マイナスなら右からの位置
str = "(123)"
str = str[1:-1]
print("str[1:-1]= ",str)
#123
#
# ゼロおよびプラスなら左からの位置
str = "(123)"
str = str[0:2]
print("str[0:2]= ",str)
#(1
#
# 終了位置を省略すると指定位置以降を出力
str = "(123)"
str = str[2:]
print("str[2:]= ",str)
#23)
str = "(123)"
str = str[-2:]
print("str[-2:]= ",str)
#3)
# 開始位置を省略すると先頭から指定位置まで出力
str = "(123)"
str = str[:2]
print("str[:2]= ",str)
#(1
str = "(123)"
str = str[:-2]
print("str[:-2]= ",str)
#(12
実行結果
文字列を文字で区切る
コード
#-ハイフンで区切る。
phones = "010-1234-5678, 033-999-9999"
lst = phones.split("-")
print(lst)
#['010', '1234', '5678, 033', '999', '9999']
#複数の文字(ハイフン、カンマ、空白)で区切る。
import re
phones = "010-1234-5678, 033-999-9999"
lst = re.split("[-, ]",phones)
print(lst)
#['010', '1234', '5678', '', '033', '999', '9999']
#空の要素ができる↑↑↑
lst = [x for x in lst if x != ""]
print(lst)
#['010', '1234', '5678', '033', '999', '9999']
#空の要素部分が詰まった↑↑↑
#↑↑↑上記と同じ結果
import re
phones = "010-1234-5678, 033-999-9999"
lst = [x for x in re.split("[-, ]",phones) if x != ""]
print(lst)
#['010', '1234', '5678', '033', '999', '9999']
@yasu transfered 0.5 KRWP to @krwp.burn. voting percent : 4.32%, voting power : 59.42%, steem power : 1932794.43, STU KRW : 1200.
@yasu staking status : 250 KRWP
@yasu limit for KRWP voting service : 0.25 KRWP (rate : 0.001)
What you sent : 0.5 KRWP
Refund balance : 0.25 KRWP [47506548 - 28179e529e5cdf20b242b3be8f48f58bec8ba520]
Thanks to python I met you. Thank you for sharing your knowledge. I made some problems for children to whom I give free python classes. I remembered it with your publication. I learn every day something new about python
I speak Spanish, I am from Venezuela. I used English to show you what I did. Greetings!
link
Thank you for your comment.
I didn't know the expression of array [::]