Adding/Edditing a string in between line of a string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • psbasha
    Contributor
    • Feb 2007
    • 440

    Adding/Edditing a string in between line of a string

    Hi

    I would like to edit the string in a give line of string.

    Code:
    Sample
    >>> str1 = 'Pnt1    1000     1       2       3      '
    >>> str2 = str1[:8]
    >>> str3 = '2000    '
    >>> str4 = str2 + str3 + str1[16:40]
    >>> str4
    'Pnt1    2000     1       2       3      '
    But for str3,I dont want to add the spaces at the tailing end knowing the filed format '8'.But I know the field width i.e '8' .Is it possible to add the spaces at the tailing end of the number,without counting the 'digits' and knowing the field format.

    Any slicing mechanism or any other idea ,will help me

    Thanks
    PSB
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by psbasha
    Hi

    I would like to edit the string in a give line of string.

    Code:
    Sample
    >>> str1 = 'Pnt1    1000     1       2       3      '
    >>> str2 = str1[:8]
    >>> str3 = '2000    '
    >>> str4 = str2 + str3 + str1[16:40]
    >>> str4
    'Pnt1    2000     1       2       3      '
    But for str3,I dont want to add the spaces at the tailing end knowing the filed format '8'.But I know the field width i.e '8' .Is it possible to add the spaces at the tailing end of the number,without counting the 'digits' and knowing the field format.

    Any slicing mechanism or any other idea ,will help me

    Thanks
    PSB
    ??
    Code:
    >>> s = '%-8d' % 36507
    >>> s
    '36507   '

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Code:
      >>> s = 'Pnt1    1000     1       2       3      '
      >>> sList = [i for i in s.split() if i != '']
      >>> sList[1] = str(34567)
      >>> outStr = ''.join(['%-8s' % s for s in sList])
      >>> outStr
      'Pnt1    34567   1       2       3       '
      >>>

      Comment

      Working...