String

Generally speaking, 2 pointer method is useful in String questions.

split()

whatever_string.split() automatically splits this string into a LIST of substrings based on whitespace characters so unlike java, no need .split(“ “)

no append() or pop() method in string

We cannot use append() or pop() method in strings because strings in Python are immutable unlike lists. Thus, we can achieve same functionality via string concatentation (+) and string slicing ([start or end index of string you want to slice])

For example, if you want to remove the first char of string and append to the back of the string

# wrong, this is for list
# s.append(s.pop(0))

s = s[1:] + s[-0]

stringHola.isDigit()

checks if string is a number

bin() to convert to binary string

s = bin(num)[2:]

It converts an integer called num to a binary string using the bin() function and slices the prefix ‘0b’. With this method, you don’t have to code everything like

def convert_to_binary(x):
    digits = []
    while x > 0:
        remainder = x % 2
        # not digits.append(remainder) 
        # because digits list will have integers, not string, and they
        # cannot be joined together with join() method at the return step
        digits.append(str(remainder))  # Convert the digit to a string
        x //= 2
    digits.reverse()
    return "".join(digits)

s.count(‘whatever you are looking for’)

# s = "1110110"
number_of_1s = s.count('1')

Errors

TypeError: sequence item 0: expected str instance, int found

When dealing with a string in integer form like “12145” and you are doing some processing with that, you are probably gonna use list. Make sure that when method expects a sequence of strings, you should pass g a sequence of strings, not integers.

For example

def convert_to_binary(x):
    digits = []
    while x > 0:
        remainder = x % 2
        # not digits.append(remainder) 
        # because digits list will have integers, not string, and they
        # cannot be joined together with join() method at the return step
        digits.append(str(remainder))  # Convert the digit to a string
        x //= 2
    digits.reverse()
    return "".join(digits)

Practice question

숫자 문자열과 영단어

https://school.programmers.co.kr/learn/courses/30/lessons/81301