用单引号''
或者 ""
括起来的任意字符表示字符串
如果字符串中既包含'
也包含 "
, 可以用转义字符来表示。
例如: str="I'm \"tux\""
str='abcdefg'
syntax | result | description |
str[0] | a | character in position 0 |
str[5] | f | character in position 5 |
str[-1] | g | the last character |
str[-2] | f | the second last character |
str[0:2] | ab | characters from position 0(include) to position 2(exclude) |
str[2:5] | cde | characters from position 2(include) to position 5(exclude) |
str[:2] | ab | characters from the beginning to position 2(exclude) |
str[:-1] | abcdef | characters from the beginning the the last character(exclude) |
str[4:] | efg | characters from position 4 to the end |
str[-2:] | fg | characters from the second last to the end |
str[-1:] | f | the last character |
str[:] | abcdefg | all the characters |
str[::-1] | gfedcba | [::-1] 字符串最后一个字符到第一个字符,也就是对字符串逆序 |
str[::-2] | geca | [::-2] 字符串逆序,间隔一个字符 |
ord将字符转换为对应的ASCII码
chr 将0-255的任一整数转换为对应的字符
string.join(iterable)
将多个字符串连接, join的参数必须是可迭代的对象,例如 list
例:
str1 = 'Hello' str2 = 'Tux' '.'.join([str1, str2])
结果为: Hello.Tux
'-'.join(str1, str2)
结果为: Hello-Tux
字符串的链接符号即调用join的字符串