Skip to main content

String

Concatenate

secret_password = 'jhk7GSH8ds'
print('Password hint: the third letter of your password is ' + secret_password[2])
# Escaping characters
introduction = 'Hello, I\'m John!'
print(introduction)

# Joining strings
user_age = 28
user_name = 'John'
greeting = user_name + ', you are ' + str(user_age) + '!'
print(greeting)
s = 'String'
s += ' Concatenation'
print(s)
# Using %
s1, s2, s3 = 'Python', 'String', 'Concatenation'
s = '%s %s %s' % (s1, s2, s3)
print(s)

# Using format()
s1, s2, s3 = 'Python', 'String', 'Concatenation'
s = '{} {} {}'.format(s1, s2, s3)
print(s)

# Using f-string
s1, s2, s3 = 'Python', 'String', 'Concatenation'
s = f'{s1} {s2} {s3}'
print(s)

Parsing

.split() : convert a string into a list

"This is another example".split()
# Return ['This', 'is', 'another', 'example']
removed_users = "wjaffrey jsoto abernard jhill awilliam"
print("before .split():", removed_users)
removed_users = removed_users.split()
print("after .split():", removed_users)

with open("update_log.txt", "r") as file:
    updates = file.read()
updates = updates.split()

.join() : convert a list into a string

approved_users = ["elarson", "bmoreno", "tshah", "sgilmore", "eraab"]
print("before .join():", approved_users)
approved_users = ",".join(approved_users)
print("after .join():", approved_users)

with open("update_log.txt", "r") as file:
    updates = file.read()
updates = updates.split()
updates = " ".join(updates)
with open("update_log.txt", "w") as file:
    file.write(updates)
# 以空白串接 List 的所有內容,輸出為字串
strings = ' '.join(my_list)

# 以空白行串接 List 的所有內容,輸出為字串
strings = '\n\n'.join(my_list)

.index() : get the index of specified character

string = "Hello, World"
print(string.index('w'))
def replace_domain(email, old_domain, new_domain):
  if "@" + old_domain in email:
    index = email.index("@" + old_domain)
    new_email = email[:index] + "@" + new_domain
    return new_email
  return email

Slicing

  • Format: string [includ-index : exclude-index]
  • Character Index: beginning with zero
  • string[-2]: the last two characters
string1 = "Greetings, Earthlings"
print(string1[0])   # Prints “G”
print(string1[4:8]) # Prints “ting”
print(string1[11:]) # Prints “Earthlings”
print(string1[:5])  # Prints “Greet”

print(string1[-10:])     # Prints “Earthlings” again
phonenum = "2025551212"

# The first 3 digits are the area code:
area_code = "(" + phonenum[:3] + ")"
# area_code is (202)

# the numbers 4–6 from the list:
exchange = phonenum[3:6]
# exchange is 555

# the last four numbers:
line = phonenum[-4:]
# line is 1212

More methods

" yes ".strip()
" yes ".lstrip()
" yes ".rstrip()
# Return 'yes'
# Return 'yes '
# Return ' yes'
"The number of times e occurs in this string is 4".count("e")
# Return 4
"Forest".endswith("rest")
# Return True
"Forest".isnumeric()
"12345".isnumeric()
# Return False
# Return True

Cheat Sheet

String Methods

python_string_method.jpg