I have a text file that contains numbers.
I need to move some of the numbers from the beginning of the file to the end in the correct order.
For example, the Original TEXT
file has the following content: 0123456789
.
I need to move the first 4 numbers to the end in the same order so it'll look like this:
4567890123.
Unfortunately i have no idea how to do this with Python, I don't know even where to start.
Any pointers to solving this problem would be highly appreciated.
See the Python tutorial ( section "Strings" ; search for "slice notation"):
>>> a = "0123456789"
>>> b = a[4:] + a[:4]
>>> b
'4567890123'
Or what is it you're really trying to do?
The individual characters of the string a = '0123456789'
can be accessed through a[i]
, where for i=0
you get the character at the first position (indexes are numbered from 0), so '0'
. You can also extract several characters at once in the form a[i:j]
, where i
is the position of the first character and j
is the position of the character after the last character. If you omit one of i
or j
, it will take all characters from the beginning or until the end of the string.
So:
a[0] = a[0:1] = a[:1] = '0'
a[1] = a[1:2] = '1'
a[4] = a[4:5] = '4'
a[0:3] = a[:3] = '012'
a[3:5] = '34'
a[4:] = '456789'
So the first 4 characters are a[:4]
and the rest is a[4:]
. Now you concatenate them together:
a[4:] + a[:4]
and it will return
'4567890123'
In order to read the file, you will have to open it in the read mode and use the first line, stripping any whitespace/newlines:
with open('filename.txt', 'r') as f:
line = f.readline().strip()
print(line[4:] + line[:4])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.