I want to do the following split:
input: 0x0000007c9226fc output: 7c9226fc
input: 0x000000007c90e8ab output: 7c90e8ab
input: 0x000000007c9220fc output: 7c9220fc
I use the following line of code to do this but it does not work!
split = element.rpartition('0')
I got these outputs which are wrong!
input: 0x000000007c90e8ab output: e8ab
input: 0x000000007c9220fc output: fc
what is the fastest way to do this kind of split?
The only idea for me right now is to make a loop and perform checking but it is a little time consuming.
I should mention that the number of zeros in input is not fixed.
Each string can be converted to an integer using int() with a base of 16. Then convert back to a string.
for s in '0x000000007c9226fc', '0x000000007c90e8ab', '0x000000007c9220fc':
print '%x' % int(s, 16)
Output
7c9226fc
7c90e8ab
7c9220fc
input[2:].lstrip('0')
That should do it. The [2:] skips over the leading 0x (which I assume is always there), then the lstrip('0') removes all the zeros from the left side.
In fact, we can use lstrip ability to remove more than one leading character to simplify:
input.lstrip('x0')
format is handy for this:
>>> print '{:x}'.format(0x000000007c90e8ab)
7c90e8ab
>>> print '{:x}'.format(0x000000007c9220fc)
7c9220fc
In this particular case you can just do
your_input[10:]
You'll most likely want to properly parse this; your idea of splitting on separation of non-zero does not seem safe at all.
Seems to be the XY problem.
If the number of characters in a string is constant then you can use
the following code.
input = "0x000000007c9226fc"
output = input[10:]
Documentation
Also, since you are using rpartitionwhich is defined as
str.rpartition(sep)
Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.
Since your input can have multiple 0's, and rpartition only splits the last occurrence this a malfunction in your code.
Regular expression for 0x00000 or its type is (0x[0]+) and than replace it with space.
import re
st="0x000007c922433434000fc"
reg='(0x[0]+)'
rep=re.sub(reg, '',st)
print rep
Related
I have complex number in the form of a string
x = 1+3j
Using the split() method of strings , I want to break it into the real and imaginary parts.
What I tried :
I used the + as a separator of the string and got the real and imaginary values.
Problem: The complex number can also be3-7j , I that case , split() fails as the string does not have a +.
What a want is that the split() should split the string when it encounters either + or -
you can try this :
import numpy as np
y=complex(x)
xr,xi=np.real(y),np.imag(y)
I don't know if you want to keep them as strings, but if you do, just add str() around np.real(y) and np.imag(y).
Note that it doesn't work with you have spaces within your string.
I have a question that ask the user to input a string THE and split it as three different string, output like this T,H,E I tried but output same with input.
def func():
str1=input("Enter String : ")
','.split(str1)
print(str1)
func()
Output
THE
And second question is that ask the user to enter a string T H E S T R I N G and the output should THE STRING when one space occurs remove it and if more then one then replace it whit single space.
Here is my code.
def func2():
str2=input("Enter String :")
for i in str2:
if(i.isspace==True):
del(i)
else:
str2=str2+i
print(str2)
func2()
output is.
T H E S T R I N GTHESTRING
I have no idea how to correct it.
You cannot store the value after splitting and not printing it.
Just change ','.split(str1) with str1 =str1.split(',') and print str1.
Read the documentation for the split method: it doesn't apply to your first problem at all. Instead, the solution is much simpler: take the individual characters and join them with commas:
char_list = list(str1)
str2 = ','.join(char_list)
... and print or return str3. Yes, this can be shortened; I'm teaching you the individual steps.
As the posting guidelines tell you, each question must have a separate posting. I'll leave the other answer for your other posting.
There's a distinction between in-place and standard operators. In-place functions actually change in the input, while standard operators give a result as output, and that output then has to be assigned or passed to something else for it to be used. (Also, you don't have the syntax correct; it should be 'str1.split(',')) The split operator is a standard operator; 'str1.split(',') doesn't affect the value of str1, but instead creates a new result. Since you're not doing anything with that result, it gets thrown away. You could do split_string ='str1.split(',') and then print(new_string) or just print('str1.split(',').
Also, the problem statements "split it as three different string" and "output like this T,H,E" are contradictory. If you want a list of three strings, that would be ['T','H','E']. Saying you want an output of T,H,E makes it sound like you want a single string with commas between the letters.
https://www.hackerearth.com/practice/algorithms/sorting/merge-sort/practice-problems/algorithm/i-think-its-easy/
the merge sort algorithm is working fine and i am able to get the same string as expected, however the output is not matching with the expected output.
n = int(raw_input())
a = [] # input list
for i in range(n):
a.append(raw_input().split())
for i in range(n):
print (' '.join(mergesort(a[i])
in the expected output for each new list of strings one extra space is present in the beginning while my code do not add any extra space at the beginning of new list of strings. why is this difference present when only one space is to be printed between two strings? how can i solve this?
my output : my_output
expected output : expected_output
below is the required output format, hence i added the space in my print function in last line .
Output:
The output should contain the set of input strings ordered by the length of strings.A blank space must be printed between two words.
Your code seems a bit confused to me. Do you really want raw_input().split()? I don't think so. Try this:
inp = raw_input()
for el in inp.split():
print(''.join(mergesort(el)))
You get the join functio wring. It merges the array into a string, separating the elements by the string on which you are calling it. In your case the space. If you want spaces at the front and the end of your string, you have to do this by hand.
print(' ', ' '.join(mergesort(a[i])))
This should do the trick.
Consider the following example
a= 'Apple'
b = a.split(',')
print(b)
Output is ['Apple'].
I am not getting why is it returning a list even when there is no ',' character in Apple
There might be case when we use split method we are expecting more than one element in list but since we are splitting based on separator not present in string, there will be only one element, wouldn't it be better if this mistake is caught during this split method itself
The behaviour of a.split(',') when no commas are present in a is perfectly consistent with the way it behaves when there are a positive number of commas in a.
a.split(',') says to split string a into a list of substrings that are delimited by ',' in a; the delimiter is not preserved in the substrings.
If 1 comma is found you get 2 substrings in the list, if 2 commas are found you get 3 substrings in the list, and in general, if n commas are found you get n+1 substrings in the list. So if 0 commas are found you get 1 substring in the list.
If you want 0 substrings in the list, then you'll need to supply a string with -1 commas in it. Good luck with that. :)
The docstring of that method says:
Return a list of the words in the string S, using sep as the delimiter string.
The delimiter is used to separate multiple parts of the string; having only one part is not an error.
That's the way split() function works. If you do not want that behaviour, you can implement your my_split() function as follows:
def my_split(s, d=' '):
return s.split(d) if d in s else s
Is there a way to manipulate a string in Python using the following ways?
For any string that is stored in dot notation, for example:
s = "classes.students.grades"
Is there a way to change the string to the following:
"classes.students"
Basically, remove everything up to and including the last period. So "restaurants.spanish.food.salty" would become "restaurants.spanish.food".
Additionally, is there any way to identify what comes after the last period? The reason I want to do this is I want to use isDigit().
So, if it was classes.students.grades.0 could I grab the 0 somehow, so I could use an if statement with isdigit, and say if the part of the string after the last period (so 0 in this case) is a digit, remove it, otherwise, leave it.
you can use split and join together:
s = "classes.students.grades"
print '.'.join(s.split('.')[:-1])
You are splitting the string on . - it'll give you a list of strings, after that you are joining the list elements back to string separating them by .
[:-1] will pick all the elements from the list but the last one
To check what comes after the last .:
s.split('.')[-1]
Another way is to use rsplit. It works the same way as split but if you provide maxsplit parameter it'll split the string starting from the end:
rest, last = s.rsplit('.', 1)
'classes.students'
'grades'
You can also use re.sub to substitute the part after the last . with an empty string:
re.sub('\.[^.]+$', '', s)
And the last part of your question to wrap words in [] i would recommend to use format and list comprehension:
''.join("[{}]".format(e) for e in s.split('.'))
It'll give you the desired output:
[classes][students][grades]
The best way to do this is using the rsplit method and pass in the maxsplit argument.
>>> s = "classes.students.grades"
>>> before, after = s.rsplit('.', maxsplit=1) # rsplit('.', 1) in Python 2.x onwards
>>> before
'classes.students'
>>> after
'grades'
You can also use the rfind() method with normal slice operation.
To get everything before last .:
>>> s = "classes.students.grades"
>>> last_index = s.rfind('.')
>>> s[:last_index]
'classes.students'
Then everything after last .
>>> s[last_index + 1:]
'grades'
if '.' in s, s.rpartition('.') finds last dot in s,
and returns (before_last_dot, dot, after_last_dot):
s = "classes.students.grades"
s.rpartition('.')[0]
If your goal is to get rid of a final component that's just a single digit, start and end with re.sub():
s = re.sub(r"\.\d$", "", s)
This will do the job, and leave other strings alone. No need to mess with anything else.
If you do want to know about the general case (separate out the last component, no matter what it is), then use rsplit to split your string once:
>>> "hel.lo.there".rsplit(".", 1)
['hel.lo', 'there']
If there's no dot in the string you'll just get one element in your array, the entire string.
You can do it very simply with rsplit (str.rsplit([sep[, maxsplit]]) , which will return a list by breaking each element along the given separator.
You can also specify how many splits should be performed:
>>> s = "res.spa.f.sal.786423"
>>> s.rsplit('.',1)
['res.spa.f.sal', '786423']
So the final function that you describe is:
def dimimak_cool_function(s):
if '.' not in s: return s
start, end = s.rsplit('.', 1)
return start if end.isdigit() else s
>>> dimimak_cool_function("res.spa.f.sal.786423")
'res.spa.f.sal'
>>> dimimak_cool_function("res.spa.f.sal")
'res.spa.f.sal'