python trying to remove single apostrophe - python

I'm using a program called CityEngine which has a python element to it.
The problem: I've just called a function on an object and returns me a list of numbers, xyz. I split the xyz into their own names. I also call a function to retrieve a different attribute related to this object to replace the previously retrieved y value.
Now, when I print the y value, it contains numerical characters only apart from decimal place.
When I incorporate the y value into a new list, it's value has single apostrophe around it.
For example, print(y) returns 5.0000000
If I place it like this position[x,y,z] I get a print(position) of [0, '5.000000' , 0]. The program can't read the single apostrophes so ignored the value completely.
I've tried .remove("'","") and .strip() and nothing.
Any help would be appreciated.
Thanks.

That looks more as if the function were not returning a number but a string. So, in order to deal with it, you’ll have to convert the string using either int() or float().
In general, if you do a print(l) on some list of items, each item will be printed with the output of it’s __repr__ method. Convention has it that the __repr__ method of string wraps the string with single apostrophes, whereas numbers do not get wrapped. This is to remove potential ambiguity. Hence, a print(l) which returned
[0, '5.00000', 0.1]
would be a list containing an int, a str and a float.

Convert it to float ... It is a string, so you need to do string to float conversion

Related

Two formatting strings in one with only one value

I want to have a string where I can format it with an integer so that it:
Adds a sign in front of the integer (+ for positive ints, - for negative ints)
Surround the signed int with parentheses (i.e. with ())
Left align the int with parentheses on the left, adding if necessary spaces to the end.
I know how to do these steps separately, but I haven't been able to combine them into a single string.
1 and 2 would be accomplished with for example '({:+d})'.format(3), this would result in (+3).
3 is done for an arbitrary string with '{:<5}'.format(3), this would result in 3 (4 trailing spaces).
My goal is to have a single string where I can call .format on only once, so
format_string.format(3)
would result in
(+3)
with one trailing space to make the string length 5.
Is this possible?
I've tried ({{:+d}:<5}) but this doesn't work as it thinks {:+d} is the field name to format with <5, which is obviously not the case.
I've also looked into f-strings, but these are not suitable for my use case as I call .format on the format string later than when it's created.
Any help would be most welcome!
Solution with one call for format:
def special_format_int(n, SPACES=5):
return '({:+d})'.format(n).ljust(SPACES)

How can I pack a string in struct.pack

I am trying to pack a string using struct.pack.
I am able to see complete value if I use integer type but when I want to use string I only see one character.
struct.pack("<1L",0xabcdabcd)
'\xab\xcd\ab\cd'
struct.pack("<1s","overflow")
'o' prints just s. I wanted it to print full string: overflow.
In the format string ("<1s") you're passing to struct.pack, the 1 denotes the maximum number of characters that field can store. (See the paragraph beginning "For the 's'..." in the struct documentation.) Since you're passing 1, it will only store the first character. You'll need to choose a length that will fit any string you want to store in the struct, and specify that. For example, to store the string "overflow" (8 characters) you could use "<8s":
>>> struct.pack("<8s", "overflow")
'overflow'

Why Simple String's Character has So many array Dimensions?

I am currently working on a python's String and List.
When I assign string in variable str="string" and try to access it first character by str[0] it works perfectly and give "s".
But, when I try to find character str[0][0][0][0][0][0] it again gives "s". But when I give str[0][1] it gives an error:
IndexError: string index out of range
Its Correct. My Question is Why Simple String Character has So many array Dimensions? and it did not given any error and print 0 character of string when str[0][0][0][0][0][0]. What is Data Structure of String?
My Code is
str="string"
print((str[0][0][0][0][0][0][0][0])) # Working, but my Question is Why Working
print((str[1][0][0][0][0])) # Working
print((str[2][0][0][0][0])) # Working
print((str[3][0][0][0][0])) # Working
list=["0","p",0]
print(list[0][0][0]) # Working
My Output is:
s
t
r
i
0
Why shouldn't it work?
Indexing a string returns a one element string which is again indexable and returns the same value:
>>> 's'[0]
's'
since it consists of one element, you can continue indexing the zero-element [0] as much as you want.
This is explained in the standard type hierarchy section of the Python Reference manual:
Strings
A string is a sequence of values that represent Unicode code points. All the code points in the range U+0000 - U+10FFFF can be represented in a string. Python doesn’t have a char type; instead, every code point in the string is represented as a string object with length 1.
(Emphasis mine)
Side-note: Don't use names such as str, you mask the built-in str.
In Python a string is a sequence of characters, but characters are 1-char strings.
So if you access 'foobar'[0], you obtain 'f'. Since f is however a string, we can access the first character of that string. Since 'f'[0] is 'f'. As a result if you access a strings s with s[i][0][0][0], you thus keep accessing the first character of the string s.
If you write s[i][1] however, this will error, since s[i] is a one-character string, and thus you can not obtain the second character, since there is no such character.
The string itself is not multidimensional, you simply obtain a new string and call the index of that new string. You can add as many [0]s as you like.
The problem is not in Python, it is due to the fact that you assume there is a char type in Python (based on the title of this question).
A string in Python is an array of essentially single element strings. s[0] simply returns the string 's', not a character. s[0]...[0] can be thought of as an infinite recursion that keeps getting the same single element string, infinitely many times.
You can go as deep as you want: (in this case, in order to do it more than 997 times you will need to modify Python`s default allowed recursion depth)
def string_dive(s, count=0):
if count < 997:
count += 1
return string_dive(s[0], count)
else:
return s
print(string_dive('string'))
# 's'

How do I remove a character from strings in a list?

I am working with a module called PyDictionary. Whenever it gets the synonym of a word, it creates a list of the synonyms, however when I try print the list, it has a 'u' before the synonym, example:
[u'welcome', u'howdy', u'hi', u'greetings', u'bonjour']
I've tried: synonym = re.sub('u','',synonym[0]), and this works, but only prints 'welcome', not the entire list.
Any help would be greatly appreciated.
Thanks!
If you want to convert the list to a list of strings you can use list comprehensions like:
result = [str(x) for x in synonym]
The u you are seeing is not part of the string content, and therefore cannot be removed with regular expression substitution. Instead, it should be considered part of the opening quote. The syntax of the Python language itself allows for string literals to be defined with quotes that are inflected in this way. For example:
a = 'spam'
b = u'spam' # in Python 2, a and b are different types
When you display the variable the way you would to a programmer, i.e. in such a way that the quote characters are visible (e.g. just typing synonym[0] at the prompt, or trying to print the whole list synonym, or otherwise invoking Python's repr() mechanism on the strings) then the u will be visible too. By contrast, when you display the variable as you would to a user (e.g. with print synonym[0], or by joining the list and then printing the resulting string) then, just as you would not expect to see the quote characters themselves, you will also not see the u.

How to strip letters out of a string and compare values?

I have just learned Python for this project I am working on and I am having trouble comparing two values - I am using the Python xlwt and xlrd libraries and pulling values of cells from the documents. The problem is some of the values are in the format 'NP_000000000', 'IPI00000000.0', and '000000000' so I need to check which format the value is in and then strip the characters and decimal points off if necessary before comparing them.
I have tried using S1[:3] to get the value without alphabet characters, but I get a 'float is not subscriptable' error
Then I tried doing re.sub(r'[^\d.]+, '', S1) but I get a Typerror: expected a string or buffer
I figured since the value of the cell that is being returned via sheet.cell( x, y).value would be a string since it is alphanumeric, but it seems like it must be returned as a float
What is the best way to format these values and then compare them?
You are trying to get the numbers from the strings in the format shown? Like to get 2344 from NP_2344? If yes then use this
float(str(S1)[3:])
to get what you want. You can change float to int.
It sounds like the API you're using is returning different types depending on the content of the cells. You have two options.
You can convert everything to a string and then do what you're currently doing:
s = str(S1)
...
You can check the types of the input and act appropriately:
if isinstance(S1, basestring):
# this is a string, strip off the prefix
elif isinstance(S1, float):
# this is a float, just use it

Categories

Resources