Can't remove \x strings - python-3.x

I made some researches to delete strings like \x__ . But it is not working.
Here is what i want to do:
i have a string like this:
j_r="some characters \xe2\x84\xc2 some other characters"
In my program, i only want to get:
"some characters some other characters"
Here is what i tried:
c=0
j_r=list(j_r)
while c < len(j_r):
if j_r[c]=='\\':
c+=3
j_f.append(j_r[c])
c+=1
print(j_f)
And here is what it prints:
['s','o','m','e',' ','c','h','a','r','a','c','t','e','r','s']
So i lost the second part of the string that i wanted to keep :'(
May someone help please.
Thank you very much.
(sorry for my english... i am french)

Try checking out this code.
The hex variables that you have created should first be checked since \xe2 is treated as on character.
j_r="some characters \xe2\x84\xc2 some other characters"
c=0
j_r=list(j_r)
j_f = list()
print('Hello World!')
while c < len(j_r):
a = int(j_r[c].encode('hex'), 16)
if(a == 32 or ((a >= 65 and a <= 90)or ( a >= 97 and a<= 122))):
j_f.append(j_r[c])
c += 1
print(j_f)
I hope this code help you with your problem.

What you're getting is bytes, and you want text from it. Therefore you need to decode it.
3>> b'Battlefield: Bad Company\xe2\x84\xa2 2'.decode('utf-8')
'Battlefield: Bad Company™ 2'

Related

Python program to count characters that fall between ! and 2 ##

i have a problem with this question:
You have a string containing !, # and small alphabets a-z. You have to escape each character that follows an ! and lies between 2 # symbols. [Treat odd # as ( and even # as ) ] You have to print out how many alphabets will be escaped.
Input Format
Input will be one line containing the string sequence
Constraints
n = len(string_seq)
1 < n < 1000
Output Format
Output will be a single integer
Sample Input 0
#!a!b#c!d
Sample Output 0
2
Sample Input 1
##bc!a#
Sample Output 1
0
Now this code clears 6 out of 9 test cases but i am not able to understand how to make it clear all the test cases i have tried many ways. My suspision is the test caeses might be wrong. Can someome help me tell me if the question is wrong or the test cases is wrong or my code is wrong and if my code is wrong please help me rectify it. Thank You.
def escape(str1):
counter=0
if(str1.count('!')%2==1):
return '0'
for a,b in enumerate(str1):
if(b=='#'):
if(97<=ord(str1[a+1])<=122):
if(str1.index('#')<a+1<len(str1)-str1[::-1].index('#')):
counter+=1
return counter
str1=input()
print(escape(str1))
Tell me if this code works for all your cases so i make my solution better..
case='#h!a!h#gh#!d##ghj#'
cnt=0
temp=''
flag=False
for c in case:
if c=='#':
if flag:
#print(temp)
tl=temp.split('!')
if len(tl)>1:
#print(tl)
#tl=list(filter(('').__ne__, tl))
#print(tl)
cnt+=len(tl)-1
temp=''
flag=False
else:
flag=True
else:
temp+=c
print(cnt)
def escape(str1):
i=0
counter=0
final_counter=0
condition1=False
while(i!=len(str1)):
if(str1[i]=='#' and condition1==False):
condition1=True
i+=1
elif(str1[i]=='#' and condition1==True):
condition1=False
final_counter+=counter
counter=0
i+=1
elif(condition1==True):
if(str1[i]=='!'):
i+=1
if(97<=ord(str1[i])<=122):
counter+=1
i+=1
else:
i+=1
else:
i+=1
return final_counter
I hope this helps.
I think that the problem asks you for the following conditions to increase your counter:
First you can start counting when a '#' appears, otherwise you can't start counting.
Then when you find a letter after a '!' (e.g !a) you increase your counter.
Finally, if another "#" you accumulate everything in your final counter which you are going to print.
Confirm me if this is correct with all your test cases.

LUA: Reading text after reading number does not work

I am struck with the io.read command in LUA. The example below jumps over the text-read line. That only happens if there is a number input before.
repeat
print("Input number!")
number=io.read("*n")
print("Would you like do to this again? (y/n)")
again = io.read()
until again == "n"
I tried this in two IDEs (repl and ZeroBrane) and it drives me MAAAD!!!
Cany anyone help, please?
Cheers,
Ulrich
Try reading line by line as string and convert string to number using tonumber()
repeat
print("Input number!")
num = tonumber(io.read())
print('Would you like do to this again? (y/n)')
again = io.read()
until again == 'n'
While debugging, I see that second io.read is using the buffer started just after your number ends.
Your code with some more prints
repeat
print("Input number!")
-- num = tonumber(io.read())
num = io.read('*n')
print('you entered-> ' .. tostring(num))
print('Would you like do to this again? (y/n)')
again = io.read()
print('your choise from (y/n)-> ' .. again)
until again == 'n'
output
Input number!
234
you entered-> 234
Would you like do to this again? (y/n)
your choise from (y/n)->
Input number!
234y
you entered-> 234
Would you like do to this again? (y/n)
your choise from (y/n)-> y
Input number!
234234n
you entered-> 234234
Would you like do to this again? (y/n)
your choise from (y/n)-> n
This description is from Programming in Lua: 21.1
The call io.read("*number") reads a number from the current input file. This is the only case where read returns a number, instead of a string. When you need to read many numbers from a file, the absence of the intermediate strings can make a significant performance improvement. The *number option skips any spaces before the number and accepts number formats like -3, +5.2, 1000, and -3.4e-23. If it cannot find a number at the current file position (because of bad format or end of file), it returns nil.
Please apologize for the poor description.

String search keep returning empty in python

I have kept trying to get my code to work but I keep getting blank output and I am not allowed to import anything e.g. RE:
choc1 =' outf.write("/# " + str(number) + " #/ " + line) #lots of cake(#) lovers here'
EC = choc1
ECout = EC
out = ""
for x in ECout :
if x!="#[a-z,A-Z]":
x = x.replace(x,"")
out += x
if out== '#lots of cake(#) lovers here':
print("well done Lucy")
else:
print(out)
I must be really stupid as this should be simple - I need to return '#lots of cake(#) lovers here' but I'm stuck on this assignment.
Any help would be greatly appreciated.
Thanks in advance - Jemma
Looking at your for loop, you are examining each character in a string individually, and comparing this to a string that is several characters long. Is this what you intended? Consider:
>>> a = "abc"
>>> for x in a:
... print(x)
...
a
b
c
Perhaps you meant to take each character, and compare that character to each character separately in the other string with a slightly different statement?

Pattern Matching BASIC programming Language and Universe Database

I need to identify following patterns in string.
- "2N':'2N':'2N"
- "2N'-'2N'-'2N"
- "2N'/'2N'/'2N"
- "2N'/'2N'-'2N"
AND SO ON.....
basically i want this pattern if written in Simple language
2 NUMBERS [: / -] 2 NUMBERS [: / -] 2 NUMBERS
So is there anyway by which i could write one pattern which will cover all the possible scenarios ? or else i have to write total 9 patterns and had to match all 9 patterns to string.... and it is not the scenario in my code , i have to match 4, 2 number digits separated by [: / -] to string for which i have towrite total 27 patterns. So for understanding purpose i have taken 3 ,2 digit scenario...
Please help me...Thank you
Maybe you could try something like (Pick R83 style)
OK = X MATCH "2N1X2N1X2N" AND X[3,1]=X[6,1] AND INDEX(":/-",X[3,1],1) > 0
Where variable X is some input string like: 12-34-56
Should set variable OK to 1 if validation passes, else 0 for any invalid format.
This seems to get all your required validation into a single statement. I have assumed that the non-numeric characters have to be the same. If this is not true, the check could be changed to something like:
OK = X MATCH "2N1X2N1X2N" AND INDEX(":/-",X[3,1],1) > 0 AND INDEX(":/-",X[6,1],1) > 0
Ok, I guess the requirement of surrounding characters was not obvious to me. Still, it does not make it much harder. You just need to 'parse' the string looking for the first (I assume) such pattern (if any) in the input string. This can be done in a couple of lines of code. Here is a (rather untested ) R83 style test program:
PROMPT ":"
LOOP
LOOP
CRT 'Enter test string':
INPUT S
WHILE S # "" AND LEN(S) < 8 DO
CRT "Invalid input! Hit RETURN to exit, or enter a string with >= 8 chars!"
REPEAT
UNTIL S = "" DO
*
* Look for 1st occurrence of pattern in string..
CARDNUM = ""
FOR I = 1 TO LEN(S)-7 WHILE CARDNUM = ""
IF S[I,8] MATCH "2N1X2N1X2N" THEN
IF INDEX(":/-",S[I+2,1],1) > 0 AND INDEX(":/-",S[I+5,1],1) > 0 THEN
CARDNUM = S[I,8] ;* Found it!
END ELSE I = I + 8
END
NEXT I
*
CRT CARDNUM
REPEAT
There is only 7 or 8 lines here that actually look for the card number pattern in the source/test string.
Not quite perfect but how about 2N1X2N1X2N this gets you 2 number followed by 1 of any character followed by 2 numbers etc.
This might help:
BIG.STRING ="HELLO TILDE ~ CARD 12:34:56 IS IN THIS STRING"
TEMP.STRING = BIG.STRING
CONVERT "~:/-" TO "*~~~" IN TEMP.STRING
IF TEMP.STRING MATCHES '0X2N"~"2N"~"2N0X' THEN
FIRST.TILDE.POSN = INDEX(TEMP.STRING,"~",1)
CARD.STRING = BIG.STRING[FIRST.TILDE.POSN-2,8]
PRINT CARD.STRING
END

cutting a string at spaces python

I am beginning to learn python and want to cut a string at the spaces; so 'hello world' becomes 'hello' and 'world'. To do this i want to save the locations of the spaces in a list, but i can't figure out how to do this. In order to find the spaces i do this:
def string_splitting(text):
i = 0
for i in range(len(text)):
if (text[i]==' '):
After saving them in the list i want to display them with text[:list[1]] (or something like that)
Can anyone help me with the saving it in a list part; and is this even possible?
(Another way to cut the string is welcome to :-) )
Thanks.
Use split:
"hello world my name is".split(' ')
It will give you a list of strings
thanks, i tried to do it without the split option, should have said that in the question..
anyways this worked;
def split_stringj(text):
a = text.count(' ')
p = len(text)
l = [-1]
x = 0
y = 1
for x in range(p):
if (text[x]==' '):
l.append(x)
y += 1
l.append(p)
print l
for x in range(len(l)-1):
print text[l[x]+1:l[x+1]]

Resources