テキスト(文字列)操作

投稿者: | 2022-03-15

text = '''生徒1 10,20,30
生徒2 40,30,20
生徒3 25,30,40
'''

text
# '生徒1 10,20,30\n生徒2 40,30,20\n生徒3 25,30,40\n'

print(text)
# 生徒1 10,20,30
# 生徒2 40,30,20
# 生徒3 25,30,40

目次

行に分割する

lines = text.splitlines()
print(lines)
# ['生徒1 10,20,30', '生徒2 40,30,20', '生徒3 25,30,40']

スペース文字で分割する

  • 生徒と点数の間はスペースがある
lines = text.splitlines()
line1 = lines[0] 
print(line1)
# '生徒1 10,20,30'

student1 = line1.split()
print(student1)
# ['生徒1', '10,20,30']

カンマで分割する

splitted_lines = [l.split() for l in lines]
print(splitted_lines)
# [['生徒1', '10,20,30'], ['生徒2', '40,30,20'], ['生徒3', '25,30,40']]

student1 = splitterd_lines[0]
student1_scores = student1[1].split(',')
print(student1_scores)
# ['10', '20', '30']
scores = []
for student in splitted_lines:
    name = student[0]
    splitted_socres = student[1].split(',')
    scores.append([name, splitted_socres])

scores
# [['生徒1', ['10', '20', '30']],
#  ['生徒2', ['40', '30', '20']],
#  ['生徒3', ['25', '30', '40']]]

計算する

  • 文字列を数値に変換する必要がある
  • printでカンマなどで連結して使った場合、変なスペースが入る(※箇所)
  • フォーマット済み文字列リテラルを使うと解消できる
for line in scores:
    name = line[0]
    english = line[1][0]
    math = line[1][1]
    language = line[1][2]
 
    ave = (int(english) + int(math) + int(language)) / 3
    
    print(name, 'の平均点は', ave, 'です')

# 生徒1 の平均点は 20.0 です ・・・※
# 生徒2 の平均点は 30.0 です
# 生徒3 の平均点は 31.666666666666668 です

# ex)
print(f'{name}の平均点は{ave}です')

# 生徒1の平均点は20.0です
# 生徒2の平均点は30.0です
# 生徒3の平均点は31.666666666666668です