This question already has an answer here:
这个问题已经有了答案:
- Is there a way to substring a string in Python? 10 answers
- 在Python中是否有一种方法可以对字符串进行子字符串连接?10个答案
I have the following string: "aaaabbbb"
我有以下字符串"aaaabbbb"
How can I get the last four characters and store them in a string using Python?
如何使用Python获取最后四个字符并将它们存储在字符串中?
2 个解决方案
#1
477
Like this:
是这样的:
>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'
This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4]
removes the same 4 characters from the end of the string:
这将分割字符串的最后4个字符。-4从字符串的末尾开始取值范围。修改后的表达式[:-4]从字符串末尾删除相同的4个字符:
>>>mystr[:-4]
'abcdefgh'
For more information on slicing see this Stack Overflow answer.
有关切片的更多信息,请参见此堆栈溢出答案。
#2
41
str = "aaaaabbbb"
newstr = str[-4:]
See : http://codepad.org/S3zjnKoD
参见:http://codepad.org/S3zjnKoD
#1
477
Like this:
是这样的:
>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'
This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4]
removes the same 4 characters from the end of the string:
这将分割字符串的最后4个字符。-4从字符串的末尾开始取值范围。修改后的表达式[:-4]从字符串末尾删除相同的4个字符:
>>>mystr[:-4]
'abcdefgh'
For more information on slicing see this Stack Overflow answer.
有关切片的更多信息,请参见此堆栈溢出答案。
#2
41
str = "aaaaabbbb"
newstr = str[-4:]
See : http://codepad.org/S3zjnKoD
参见:http://codepad.org/S3zjnKoD