python勉強メモ: strings

  • string concatenation
  str1 = "hello"

  str2 = "mike"

  str3 =str1+str2

  print str3

実行結果: hellomike

+記号は文字列を繋げる。

  • raw_input()で取得したものは文字列になる。数字に変換するにはfloat()かint()を使う。

  • square brackets[]から文字列から一個ずつ文字を取り出せる。始まりは0だ。

  namae = "doreen"

  n = 2

  print namae[0]

d

  print namae[n]

r

  • len()は文字列の長さを数えてくれる。
  len(doreen)

6

  • looping through strings

    コード:

  namae = "doreen"
  
  for letter in namae:

      print letter

実行:  

d

o

r

e

e

n

  • slicing string

    • The second number is one beyond the end of the slice - “up to but not including”

    • If the second number is beyond the end of the string, it stops at the end.

    • If we leave off the first number or the last number of the slice, it is assumed to be the beginning or end of the string respectively

    コード:

  namae = "doreen python"
 
  print namae[0:1]

  print namae[2:4]

  print namae[5:8]

  print namae[8:20]

  print namae[8:]

  print namae[:3]

  print namae[:]

結果:

d

re

n p

ython

ython

dor

doreen python

  • string library

    • Python has a number of string functions which are in the string library.

    • These functions are already built into every string - we invoke them by appending the function to the string variable.

    • These functions do not modify the original string, instead they return a new string that has been altered.

    コード:

  namae = "DOREEN"

  print namae.lower()

結果:

doreen

 なお、dir(namae)で入力すれば、「namaeに対してどんなことができるの?」という質問をpythonにすることになる。

 pythonはこれに対して、使えるメソッドをすべて返してくれる。

 各functionの詳しい説明はhttps://docs.python.org/2/library/stdtypes.html#string-methodsを参照

  • find()

    • find() finds the first occurance of the substring

    • If the substring is not found, find() returns -1

    • Remeber that string position starts at zero

    コード:

  namae = "doreen"

  pos = namae.find("or")

  pos_b = namae.find("f")

  print pos

  print pos_b

結果:

1

-1 - upper()

コード:

  namae = "doreen"

  print namae.upper()

結果:

DOREEN

  • Searh and Replace

    • The replace() function is like a “search and replace” operation in a word processor

    • it replaces all occurrences of the search string with the placement string

    code:

  namae= "hello doreen"

  new_namae = namae.replace("doreen","dandelion")

  print new_namae

result:

hello dandelion

code:

  namae= "hello doreen"

  new_namae = namae.replace("e","E")

  print new_namae

result:

hEllo dorEEn

  • Stripping Whitespace

    • Sometimes we want to take a string and remove whitespace at the beginning and/or end

    • lstrip() and rstrip() to the left and right only

    • strip() removes both begin and ending whitespace

    code:

  namae= " hello doreen "

  namae.lstrip()

–>“hello doreen ”

  namae.rstrip()

–>“ hello doreen”

  namae.strip()

–>“hello doreen”

  • Prefixes

    code:

  line = "please have a nice day"

  line.startswith("please")

–>True

  line.startswith("P")

–>False