strip(), split()的区别
这是我总是在混淆使用的点,究其原因,我想可能是混淆了两者的翻译,从而对它们的使用也经常乱用一通。
strip:剥去,剥夺;to remove something that covers something
split:劈开,分离;to divide into smaller groups
split:
method split
takes the separator character(s) as a string argument, and returns the contents of the target string as a list of strings, separated at the separator.
split方法将分隔符作为字符串参数,并将目标字符串的内容作为字符串列表返回,并在分割符处分割。
上面这话读起来总觉得拗口,现在以同一句话为例讲split的不同用法,就能明白:
-
split()
string = "Little do you know, how I'm breaking while you fall asleep; I will be alright." a = string.split() print(a) # ['Little', 'do', 'you', 'know,', 'how', "I'm", 'breaking', 'while', 'you', 'fall', 'asleep;', 'I', 'will', 'be', 'alright.']
-
split(",")
string = "Little do you know, how I'm breaking while you fall asleep." a = string.split(",") print(a) # ['Little do you know', " how I'm breaking while you fall asleep; I will be alright."]
不难看出,split
就是把括号中的符号视为分割标志,当遇到这个符号时,就自动切一刀,把字符串分为两个部分,并且以list的形式返回。
另外,split()
和split(" ")
的效果相同。
strip:
strip
removes all spaces, line breaks, tabs and other characters which would not normally be printed out,from the beginning and end of a string.
这个很好理解,就是strip会移除字符串开头和结尾的spaces、tabs等等。
string = " To see a world in a grain of sand "
b = string.strip()
print(b)
# To see a world in a grain of sand
strip括号内通常不加东西,而且它的作用部位限于字符串的开头和结尾。如果只想单独移除开头的,可以使用lstrip.()
,单独移除结尾的,可以使用rstrip.()
。
综上,这两个其实压根没有相同之处,希望之后也不会再出错了。