0
0

More than 1 year has passed since last update.

【Python】文字列をn文字に分割する

Last updated at Posted at 2021-11-12

環境

Python 3.9.2

関数

import re

def split_n(text, num, fraction=True):
    if fraction:
        return re.findall(f'.{{1,{num}}}', text) 
    else:
        return re.findall(f'.{{{num}}}', text)

利用例

# 端数も返す
print(split_n("abcdefgh", 3))
# => ['abc', 'def', 'gh']

# 端数を返さない
print(split_n("abcdefgh", 3, fraction=False))
# => ['abc', 'def']

関数化までは不要な場合

import re

# 端数も返す
print(re.findall('.{1,3}', "abcdefgh"))
# => ['abc', 'def', 'gh']

# 端数を返さない
print(re.findall('.{3}', "abcdefgh"))
# => ['abc', 'def']
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