简体   繁体   English

字符串格式,从右到左修剪

[英]String formatting, trim from right instead of left

I have a set of strings that I want to format to keep the string at 5 characters. 我有一组要格式化的字符串,以将字符串保留为5个字符。 I'm using a line like this (the original strings are sometimes 5 characters, sometimes 6): 我正在使用这样的行(原始字符串有时是5个字符,有时是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 : 您可以使用format

ram1 = '3941'
print '{0:0>5s}'.format(ram1)
## 03941

where the characters after : describe the format (0-padded 5-character long string). 后面的字符:描述格式(0填充的5个字符的长字符串)。

You can also use zfill : 您也可以使用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. 既然您提到了astype ,它看起来ram是一个NumPy数组。

To remove all 0 s from the right size of each value, use np.char.rstrip : 要从每个值的正确大小中删除所有0 ,请使用np.char.rstrip

np.char.rstrip(ram, '0')

To preserve just the first 5 bytes for each value, 要仅保留每个值的前5个字节,

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: 正如Padraic Cunningham指出的那样 ,如果您有一个字符串数组:

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. 因此,如果要保留字符串的前5个字节,请不要使用astype(int)

If you are working with numpy array containing string then astype will work fine. 如果您正在使用包含字符串的numpy数组,则astype将正常工作。

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 如果字符串长度不少于5个字符,则可以使用以下代码

a = "abcdef"

print a[0:5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM