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
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)