"""
File: strings.py
Purpose: Code implementing string objects (corresponding to the Fortran
CHARACTER type) in the code generated by for2py.
Usage: see the document "for2py: Miscellaneous constructs"
"""
[docs]class String:
def __init__(self, length = 0, value = ""):
if length > 0:
self._length = length
else:
self._length = len(value)
# Before value is assigned to self._val, it may need to be adjusted
# if len(value) != length
self.set_(value)
[docs] def value(self, obj):
if isinstance(obj, String):
return obj._val
else:
return obj
[docs] def padding(self, n):
"""padding() returns a string of blanks of length = sef._length - n."""
if n < self._length: # pad with blanks
k = self._length - n
pad_str = " " * k
else:
pad_str = ""
return pad_str
[docs] def set_(self, strval):
s = self.value(strval)
n = len(s)
if n < self._length:
adjusted = s + self.padding(n)
else:
adjusted = s[:self._length] # truncate to self._length
self._val = adjusted
def __len__(self):
return self._length
def __add__(self, other):
"""String concatenation"""
return self._val + self.value(other)
def __radd__(self, other):
"""String concatenation"""
return self.value(other) + self._val
[docs] def adjustl(self):
"""adjustl() implements the ADJUSTL() function of Fortran. This
function removes leading blanks and adds blanks on the right
so that the result is the same length as the input string."""
s = self._val.lstrip()
pad_str = self.padding(len(s))
return s + pad_str
[docs] def adjustr(self):
"""adjustr() implements the ADJUSTR() function of Fortran. This
function removes trailing blanks and adds blanks on the left
so that the result is the same length as the input string."""
s = self._val.rstrip()
pad_str = self.padding(len(s))
return pad_str + s
[docs] def f_index(self, substring, direction=[]):
"""f_index() implements the string search function of Fortran's INDEX()
function; we use the name f_index to emphasize that the behavior of
Fortran's INDEX() is slightly different from that of Python's index().
f_index() returns the position within a string where substring
first occurs; 0 if there is no such occurrence. If the argument
direction contains "back" the string is searched backwards starting
from the end."""
substr = self.value(substring)
if "back" in direction:
pos = self._val.rfind(substr)
else:
pos = self._val.find(substr)
return pos + 1
[docs] def len_trim(self):
return len(self._val.rstrip())
[docs] def repeat(self, n):
return self._val * n
[docs] def trim(self):
return self._val.rstrip()
[docs] def get_substr(self, i, j):
"""get_substr(i, j) returns the substring of the given string beginning
at position i (start position = 1) and ending at position j."""
return self._val[(i-1):j]
[docs] def set_substr(self, i, j, other):
# extract the substring
substr = self.value(other)[:(j-i+1)]
# construct the new string value
newstr = self._val[:(i-1)] + substr + self._val[j:]
# update
self.set_(newstr)
def __str__(self):
return self._val