在Python中,str類型是一個非常靈活和強大的數據類型,有許多高級技巧可以幫助你更好地使用它。以下是一些常見的高級技巧:
name = "Alice"
age = 25
sentence = "My name is {} and I am {} years old.".format(name, age)
print(sentence)
multiline_str = '''
This is a
multiline
string
'''
print(multiline_str)
sentence = "Hello, world!"
words = sentence.split()
new_sentence = " ".join(words)
print(new_sentence)
sentence = "Hello, world!"
new_sentence = sentence.replace("Hello", "Hi")
print(new_sentence)
sentence = "Hello, world!"
substring = sentence[7:12]
print(substring)
name = "Alice"
age = 25
sentence = "My name is %s and I am %d years old." % (name, age)
print(sentence)
這些只是一些常見的高級技巧,Python的str類型還有許多其他用法和功能。通過熟練掌握這些技巧,你可以更好地利用字符串來處理和操作數據。