I have a set of strings that I want to format to keep the string at 5 characters. I'm using a line like this (the original strings are sometimes 5 characters, sometimes 6):
ram1 = ram1.astype('|S5')
However, this turns
039410
Into
39410
When I want it to be
03941
Is there a simple way to fix my line of code to do this?
Cheers!
You can use format
:
ram1 = '3941'
print '{0:0>5s}'.format(ram1)
## 03941
where the characters after :
describe the format (0-padded 5-character long string).
You can also use zfill
:
print ram1.zfill(5)
## 03941
In case you need to truncate your string, you can use the following format:
print '{:.5s}'.format('039410')
## 03941
Since you mentioned astype
, it appears ram
is a NumPy array.
To remove all 0
s from the right size of each value, use np.char.rstrip
:
np.char.rstrip(ram, '0')
To preserve just the first 5 bytes for each value,
ram.astype('|S5')
suffices.
For example,
import numpy as np
ram = np.array(['039410', '123456', '00000']).astype('|S6')
print(np.char.rstrip(ram, b'0'))
# ['03941' '123456' '']
print(ram.view('|S5'))
# ['03941' '12345' '00000']
As Padraic Cunningham points out , if you have an array of strings:
In [209]: ram = np.array(['039410', '123456', '00000']).astype('|S6'); ram
Out[209]:
array([b'039410', b'123456', b'00000'],
dtype='|S6')
and convert the strings to ints, you lose zeros on the left:
In [210]: ram.astype(int)
Out[210]: array([ 39410, 123456, 0])
So do not use astype(int)
if you wish to preserve the first 5 bytes of the string.
If you are working with numpy array containing string then astype will work fine.
string = np.array('039410')
print string
## 039410
string = string.astype('|S5')
print string
## 03941
If you are working on list of strings then you should do this.
str_list = ['039410']
index = 0
for i in str_list:
i = i[:5]
str_list[index] = i
index += 1
print str_list
## ['03941']
If you are working on single string then you just have to do this
str_num = '039410'
str_num = str_num[:5]
print str_num
## '03941'
if the string length is not less than 5 character then you can use the below code
a = "abcdef"
print a[0:5]
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.