Python MIT OCW Lec3 : String Manipulation

김재만·2023년 9월 18일
0

Python MIT OCW

목록 보기
3/9

배울 내용

  1. String manipulation

1. String manipulation

Strings

  • Think of as a sequence of case sensitive characters

  • can compare strings with ==, >, <, etc

  • len() : retrieve the length of the string in the parantheses

    s = "abc"
    print(len(s)) # 3

Indexing

  • Use square brackets to perform indexing into a string
# s =     "a  b  c"
# index :  0  1  2
# index : -3 -2 -1

s = "abc"
print(s[0]) # a
print(s[1]) # b
print(s[2]) # c
# print(s[3]) # trying to index out of bounds, error
print(s[-1]) # c
print(s[-2]) # b
print(s[-3]) # a

Slicing

  • Can slice strings using [start : stop : step]
  • if give two numbers, [start : stop], step = 1 by default
  • you can also omit numbers and leave just colons
s = "abcdefgh"
print(s[3 : 6]) # "def"
print(s[3 : 6 :2]) # "df"
print(s[::]) # "abcdefgh"
print(s[::-1]) "hgfedcba"
print(s[4:1:-2]) "ec"

Mutablility

  • Strings are immutable
    : An actual string object, onece it's created, cannot be modified
s = "hello"

# s[0] = 'y' # gives an error
s = 'y' + s[1:len(s)] # allowed, s bound to new object
print(s) # yello

Strings and Loops

  • for loops
    : range is a way to iterate over numbers, but for loop can iterate over any set of values, not just numbers
  • Compare two loops
    : Bottom one is more "pythonic"
s = "abcdefgh"
for index in range(len(s)) : 
  if s[index] == 'i' or s[index] == 'u' : 
    print("There is an i or u")
s = "abcdefgh"
for char in s : 
  if char == 'i' or char == 'u' : 
    print("There is an i or u")
profile
Hardware Engineer가 되자

0개의 댓글