Python: '%2s'% doesn't work after breaking the row - python

i need to produce output with specified number of spaces. It is a table with some columns, for saving output in to the file i use line:
save_line = ('%8s' % label[each_atom + str(int(k) + 1)] +
'%10s' % str(int(i) + 1) +
'\n' +
'%2s' % x[i] +
'%20s' % y[i] +
'%20s' %z[i] +
'\n')
but the '%2s'%x[i] doesn't produce two spaces in output. I cant use +" "+ there. Any ideas what I can do?
Here is output of my code:
C1 1
2.482705 1.332897 13.175184
And finally here's how my output should looks (it is example from another input, my task is to produce my basing on this):
C1 1
2.42416980 4.14117720 4.71196000
It is no problem to change any number of spaces between any columns. The only one that doesn't work is the first one in every second row. It doesn't mater that the numbers don't mach. The problem is in the spaces.

Please combine those templates
save_line = "%8s%10s\n%2s%20s%20s\n" % (
label[each_atom + str(int(k) + 1)],
str(int(i) + 1),
x[i],
y[i],
z[i])
The right side of the % operator should be a tuple. None of your values are tuples (from what I can see) and that's a great way to get output you do not expect. If you only want to format one item:
print "Hello %s!" % ("world",)
Note the trailing comma. This is because
("World")
is a string (with parenthesis around it), while
("World",)
is a tuple containing one item.

but the '%2s'%x[i] doesn't produce two spaces in output. I cant use +" "+ there. Any ideas what I can do?
Why?
The number after % is the size of a new string field.
print '%3s' % 'why'
>>why
print '%4s' % 'why'
>> why
The size is 4 symbols for 'why' string = ' why'.
You have only 1 left space for 3 letters word if you use '%4s'.
Also, you can use '-'.
If your string is 's' and you use '%-2s', you will get new string 's ', with 1 space after your string. You can use it also in your string formatting tasks.
>>> print "%-5s%s" % ("N", "Q")
N Q
>>> print "%5s%s" % ("N", "Q")
NQ
>>> print "%5s%5s" % ("N", "Q")
N Q
>>> '%.1s' % 'Hello!'
'H'
>>> '%.2s' % 'Hello!'
'He'
And you can use value for tuple:
>>> '%.*s' % (2, 'Hello!')
'He'
Thank you,

Related

Using "%s" in python with str() and in a for loop

I'm writing this code
for n in filtered_list:
for a in range(1,3):
duplicate = str(filenameRegex.group(1) + "(" + n + ")" + filenameRegex.group(2))
I've been wondering is there a more concise way to write this? I mean the "(" + n + ")" part. I was thinking about something like %s s = n, but I don't know and couldn't trial-and-error how to use it in this case.
In this case, you have to use %d instead of %s because n is an integer, not a string !
for n in filtered_list:
for a in range(1, 3):
duplicate = "%s(%d)%s" % (filenameRegex.group(1), n, filenameRegex.group(2))
This is old-school formatting, though. In Python 3 you can use f-strings:
for n in filtered_list:
for a in range(1, 3):
duplicate = f"{filenameRegex.group(1)}({n}){filenameRegex.group(2)}"
you can try like this:
duplicate = "%s(%s)%s"%(filenameRegex.group(1),n,filenameRegex.group(2))
or
duplicate = "{0}({1}){2}".format(filenameRegex.group(1),n,filenameRegex.group(2))

Returning original string with symbols between each character

I'm trying to make my program return the exact same string but with ** between each character. Here's my code.
def separate(st):
total = " "
n = len(st + st[-1])
for i in range(n):
total = str(total) + str(i) + str("**")
return total
x = separate("12abc3")
print(x)
This should return:
1**2**a**b**c**3**
However, I'm getting 0**1**2**3**4**5**6**.
You can join the characters in the string together with "**" as the separator (this works because strings are basically lists in Python). To get the additional "**" at the end, just concatenate.
Here's an example:
def separate(st):
return "**".join(st) + "**"
Sample:
x = separate("12abc3")
print(x) # "1**2**a**b**c**3**"
A note on your posted code:
The reason you get the output you do is because you loop using for i in range(n): so the iteration variable i will be each index in st. Then when you call str(total) + str(i) + str("**"), you cast i to a string, and i was just each index (from 0 to n-1) in st.
To fix that you could iterate over the characters in st directly, like this:
for c in st:
or use the index i to get the character at each position in st, like this:
for i in range(len(st)):
total = total + st[i] + "**"
welcome to StackOverflow!
I will explain part of your code line by line.
for i in range(n) since you are only providing 1 parameter (which is for the stopping point), this will loop starting from n = 0, 1, 2, ... , n-1
total = str(total) + str(i) + str("**") this add i (which is the current number of iteration - 1) and ** to the current total string. Hence, which it is adding those numbers sequentially to the result.
What you should do instead is total = str(total) + st[i] + str("**") so that it will add each character of st one by one
In addition, you could initialize n as n = len(st)

letter shifting program in python

Let's say that I have a list of the alphabet:
ALPHABET = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
and lets say the shift positions are
0, 2, 19
if the input is a string
string = "xyz"
and I want to shift these 3 characters using the above shift positions of 0,2,19
as in shift 'x' 0 times to the right, shift 'y' 2 times to the right, and shift z 19 times to the right.
The only thing that comes to mind is something like the index() function of lists
I also see another problem. IF I shift 'z' 19 times to the right I will get an list index out of range error. If 'z' is shifted 19 times to the right I want it to become 's' which would be 19 shifts going around the list and starting from the beginning. Same thing with 'y' if I shift it to the right 2 times I want it to become 'a' etc....
Any suggestions on what to use?
So my way is more basic than TheSoundDefense but it works pretty well when you input three letters like "xyz". (Im guessing you can come up with a check to make sure they did so)
The main tool that i use is the index function which will match an item in the list and will give me the placement number for that item. Then I take that number and I add it to the numbers you gave. But then I divide it against the length and take the remainder. I don't care how many times it divides out to be, i just want the remainder because that tells me where its at in the alphabet. then I replace the letters and print them out.
ALPHABET = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
print "Please enter three letters"
x = list(raw_input("> ").upper())
length = len(ALPHABET)
first_letter = ALPHABET.index(x[0])
first_letter = (first_letter + 0) % length
x[0] = ALPHABET[first_letter]
second_letter = ALPHABET.index(x[1])
second_letter = (second_letter + 2) % length
x[1] = ALPHABET[second_letter]
third_letter = ALPHABET.index(x[2])
third_letter = (third_letter + 19) % length
x[2] = ALPHABET[third_letter]
print ''.join(x)
EDIT: I just realized I was probably answering a totally different question, because my brain doesn't understand the word "shift" properly. So instead of generating new letters, I'm generating an entirely new alphabet. Feel free to point and laugh.
For handling the out-of-range problem, you'll want to use the modulus function % to make the number "wrap around". You can use this in conjunction with slicing in order to get your shift.
ALPHABET = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
inputstring = "XYZ"
def shift(inputstr, shift1, shift2, shift3):
new_alphabet = list(ALPHABET)
shifts = [shift1, shift2, shift3]
for i in range(0,3):
inputchar = inputstr[i]
i1 = new_alphabet.index(inputchar)
i1_adjust = (i1 + shifts[i]) % len(new_alphabet)
temp_alphabet = new_alphabet[:i1] + new_alphabet[i1+1:]
new_alphabet = temp_alphabet[:i1_adjust] + [inputchar] + temp_alphabet[i1_adjust:]
print new_alphabet
# We call it here.
shift(inputstring,0,2,19)
We're basically finding the index of our character and adding our shift amount to it. Then we pull that character out of our alphabet and move along i1_adjust number of spaces to the new position. We pull the alphabet apart at that position, insert the character, and glue it back together. The code could probably be more elegant if shift1, shift2, shift3 was changed to a list of shift positions, but the proof of concept is there.
Can i solve this way: Let me know if you don't like this solution in comment, I will remove it. ( instead of down-voting )
#!/usr/bin/python
alpha = ['A','B','C','D','E','F','G','H','I',\
'J','K','L','M','N','O','P','Q','R',\
'S','T','U','V','W','X','Y','Z']
def shift_right(char, shift_inx):
dic1 = dict(zip(alpha, range(26)))
dic2 = dict(zip(range(26), alpha))
total = len(alpha)
nxt_inx = dic1[char] + shift_inx
if nxt_inx <= 25:
return dic2[nxt_inx]
else:
return dic2[nxt_inx % total]
def main():
for x,y in [('X', 0), ('Y', 2), ('Z', 19)]:
print '%s => %s => %s' % ( x, y, shift_right(x, y))
if __name__ == '__main__':
main()
Output:
X => 0 => X
Y => 2 => A
Z => 19 => S
OR
#!/usr/bin/python
alpha = ['A','B','C','D','E','F','G','H','I',\
'J','K','L','M','N','O','P','Q','R',\
'S','T','U','V','W','X','Y','Z']
def shift_right(char, shift_inx):
total = len(alpha)
nxt_inx = alpha.index(char) + shift_inx
if nxt_inx <= 25:
return alpha[nxt_inx]
else:
return alpha[nxt_inx % total]
def main():
for x,y in [('X', 0), ('Y', 2), ('Z', 20)]:
print '%s => %s => %s' % ( x, y, shift_right(x, y))
if __name__ == '__main__':
main()

formatting list to convert into string

Here is my question
count += 1
num = 0
num = num + 1
obs = obs_%d%(count)
mag = mag_%d%(count)
while num < 4:
obsforsim = obs + mag
mylist.append(obsforsim)
for index in mylist:
print index
The above code gives the following results
obs1 = mag1
obs2 = mag2
obs3 = mag3
and so on.
obsforrbd = parentV = {0},format(index)
cmds.dynExpression(nPartilce1,s = obsforrbd,c = 1)
However when i run the code above it only gives me
parentV = obs3 = mag3
not the whole list,it only gives me the last element of the list why is that..??
Thanks.
I'm having difficulty interpreting your question, so I'm just going to base this on the question title.
Let's say you have a list of items (they could be anything, numbers, strings, characters, etc)
myList = [1,2,3,4,"abcd"]
If you do something like:
for i in myList:
print(i)
you will get:
1
2
3
4
"abcd"
If you want to convert this to a string:
myString = ' '.join(myList)
should have:
print(myString)
>"1 2 3 4 abcd"
Now for some explanation:
' ' is a string in python, and strings have certain methods associated with them (functions that can be applied to strings). In this instance, we're calling the .join() method. This method takes a list as an argument, and extracts each element of the list, converts it to a string representation and 'joins' it based on ' ' as a separator. If you wanted a comma separated list representation, just replace ' ' with ','.
I think your indentations wrong ... it should be
while num < 4:
obsforsim = obs + mag
mylist.append(obsforsim)
for index in mylist:
but Im not sure if thats your problem or not
the reason it did not work before is
while num < 4:
obsforsim = obs + mag
#does all loops before here
mylist.append(obsforsim) #appends only last
The usual pythonic way to spit out a list of numbered items would be either the range function:
results = []
for item in range(1, 4):
results.append("obs%i = mag_%i" % (item, item))
> ['obs1 = mag_1', 'obs2 = mag_2', 'ob3= mag_3']
and so on (note in this example you have to pass in the item variable twice to get it to register twice.
If that's to be formatted into something like an expression you could use
'\n'.join(results)
as in the other example to create a single string with the obs = mag pairs on their own lines.
Finally, you can do all that in one line with a list comprehension.
'\n'.join([ "obs%i = mag_%i" % (item, item) for item in range (1, 4)])
As other people have pointed out, while loops are dangerous - its easier to use range

Python / Regex: exclude everything except one thing

Suppose I have these strings:
a = "hello"
b = "-hello"
c = "-"
d = "hell-o"
e = " - "
How do I match only the -(String C)? I've tried a if "-" in something but obviously that isn't correct. Could someone please advise?
Let's say we put these strings into a list, looped through and all I wanted to extract was C. How would I do this?
for aa in list1:
if not re.findall('[^-$]'):
print aa
Would that be too messy?
If you want to match only variable c:
if '-' == something:
print 'hurray!'
To answer the updates: yes, that would be too messy. You don't need regex there. Simple string methods are faster:
>>> lst =["hello", "-hello", "-", "hell-o"," - "]
>>> for i, item in enumerate(lst):
if item == '-':
print(i, item)
2 -
as a regex its "^-$"
If what you're trying to do is strip out the dash (i.e. he-llo gives hello), then this is more of a job for generator expressions.
''.join((char for char in 'he-llo' if char != '-'))
if "-" in c and len(c) ==1 : print "do something"
OR
if c=="-"

Categories