Python How to scan for a certain letter in a input - python

So, I'm making some code that I want it to do a if statement that looks through the input and if it sees a certain character will then go print a message.
password = input("password: ")
if(password == "scan for a certain letter or something"):
print("Please use don't use these smybols: / \ ; : , . > < ? ! # # $ % ^ & * ( ) [ ] { } | ")
it dosen't have to be a if statement if that is what it turns out to be, I just want to know how to do it.

You can use the in operator with the any() function:
prohibited = set("/ \ ; : , . > < ? ! # # $ % ^ & * ( ) [ ] { } | ]".split())
password = input("password: ")
if any(char in prohibited for char in password):
print(f"Please use don't use these symbols: {prohibited}")

I think it will be more convenient for the user to get an exhaustive list of invalid characters used by him so that he can correct the input:
unacceptable_symbols = r"/\;:,.><?!##$%^&*()[]{}| "
password = r"f;kjad%9203)29e2" # test string
lst = [x for x in password if x in unacceptable_symbols] # makes list of all used unacceptable symbols
if len(lst) > 0:
print("You have used the following unacceptable characters: " + ' '.join(lst))
print("Please don't use these symbols: " + ' '.join(list(unacceptable_symbols)))
# Output:
# You have used the following unacceptable characters: ; % )
# Please don't use these symbols: / \ ; : , . > < ? ! # # $ % ^ & * ( ) [ ] { } |

I have tried to implement this code with very simple logic. And its working perfectly.
s="/ ; : , . > < ? ! # # $ % ^ & * ( ) [ ] { } | \ "
s1=s.split()
s3=input("enter the string: ")
for i in s3:
if(i in s1):
print("please dont use the given symbol:",i)

Related

"sh: no closing quote" When trying to make an ASCII echo convert script

I'm trying to convert an ASCII art file to an echo command which can run it without any errors, I'm getting an error when it tries to run the script at the last line, the error is:
sh: no closing quote
I probably made my script the wrong way, how would I fix it?
The script:
import sys, os
text = sys.stdin.read()
full = "echo -e \""
chars_to_escape = ["!",'"',"#","$","&","'","(",")","*",";","<",">","?",
for char in text:
if char in chars_to_escape:
full += f"\"\{char}\""
else:
full += char
print(full)
os.system(full)
The ASCII art:
,--.
{ }
K, }
/ `Y`
_ / /
{_'-K.__/
`/-.__L._
/ ' /`\_}
/ ' /
____ / ' /
,-'~~~~ ~~/ ' /_
,' ``~~~%%',
( % Y
{ %% I
{ - % `.
| ', % )
| | ,..__ __. Y
| .,_./ Y ' / ^Y J )|
\ |' / | | ||
\ L_/ . _ (_,.'(
\, , ^^""' / | )
\_ \ /,L] /
'-_`-, ` ` ./`
`-(_ )
^^\..___,.--`
I forgot to add the last quote to the full variable.

IndexError: string index out of range python problem

I'm working on a game that called 'i will guess the name ur thinking of ' or 'guess my name'.
The user will enter a letter and the program will try to guess what position of it by using a "for loop" in python:
list_of_names = [ ]
userinput_letter = input('QUESTION : write a letter the name has: ')
new_list_of_names = [ ]
for names in list_of_names :
if userinput_letter in list_of_names :
new_list_of_names.append(names)
randomname = random.choice(new_list_of_names]
position_of_userletter = randomname.find(userinput_letter)
yn = input('QUESTION : does this letter "'+ userinput_letter +'" in the position "'+ str(position_of_userletter ) +'" (yes/no): ' )
if (yn == 'yes') :
newlist_ofnames = [ ]
for namesyes in new_list_of_names:
if ( namesyes in userinput_letter [position_of_userletter] ) :
newlist_ofnames.append(namesyes)
print(newlist_ofnames)
IndexError: string index out of range
As far as I understand userinput_letter is just one letter and you are trying to get some index in it. That's why you are getting error.
You should do smth like
if (len(namesyes) => position_of_userletter and namesyes[position_of_userletter] == userinput_letter):
First of all on line 5 you should have placed names instead of list_of_names.
Secondly you should place a loop that would re-run random choice if yn is equal to 'no'.
Then instead of this line:
if ( namesyes in userinput_letter [position_of_userletter] ) :
place this line:
if (namesyes[postition_of_userletter]== userinput_letter):
Hope it works :)

Extracting the values within the square braces

I have a file testfile with the set of server names as below.
app-server-l11[2-5].test.com
server-l34[5-8].test.com
dd-server-l[2-4].test.com
Can you please help in getting output to be as follow.
app-server-l112.test.com
app-server-l113.test.com
app-server-l114.test.com
app-server-l115.test.com
server-l345.test.com
server-l346.test.com
server-l347.test.com
server-l348.test.com
dd-server-l2.test.com
dd-server-l3.test.com
dd-server-l4.test.com
With GNU awk for the 3rd arg to match():
$ awk 'match($0,/(.*)\[([0-9]+)-([0-9]+)\](.*)/,a){for (i=a[2]; i<=a[3]; i++) print a[1] i a[4]}' file
app-server-l112.test.com
app-server-l113.test.com
app-server-l114.test.com
app-server-l115.test.com
server-l345.test.com
server-l346.test.com
server-l347.test.com
server-l348.test.com
dd-server-l2.test.com
dd-server-l3.test.com
dd-server-l4.test.com
In GNU awk:
$ awk -F"[][]" '{split($2,a,"-"); for(i=a[1];i<=a[2];i++) print $1 i $3}' file
app-server-l112.test.com
app-server-l113.test.com
app-server-l114.test.com
app-server-l115.test.com
server-l345.test.com
server-l346.test.com
server-l347.test.com
server-l348.test.com
dd-server-l2.test.com
dd-server-l3.test.com
dd-server-l4.test.com
split to fields by [ and ] using FS
use split the get the range start (a[1]) and end (a[2])
iterate the range with for and output
There is no checking whether there was a range or not. It could be implemented with something like: print (NF==3 ? $1 i $3 : $1 ).
Worst and ugliest example:
var='app-server-l11[2-5].test.com'
for i in range(int(var[(var.find('[') +1)]), int(var[(var.find("]") - 1)])+1):
print 'app-server-l11' + str(i) + '.test.com'
Use your imagination!
ser_nm = ['app-server-l11[2-5].test.com','server-134[5-8].test.com','dd-server-[2-4].test.com']
for nm in ser_nm:
for i in range(int(nm[nm.find('[')+1 : nm.find('-',(nm.find('[')+1))]), int(nm[nm.find('-',(nm.find('[')+1))+1:nm.find(']') ] )+1):
print(nm[:nm.find('[')] + str(i) + nm[nm.find(']')+1:])
This will also take care of cases where server names are like this:
'server-134[52-823].test.com'
not the best solution, but it works...
inp = open('input.txt', 'r+').read()
print(inp)
result= ''
for i in inp.split('\n'):
if len(i) > 1:
print(repr(i))
f1 = i.find('[')
f2 = i.find(']')+1
b1 = i[:f1]
b2 = i[f2:]
ins = i[f1:f2]
ins = ins[1:-1]
for j in range(int(ins.split("-")[0]),int(ins.split("-")[1])+1):
result+=b1+str(j)+b2+'\n'
outp = open('output.txt', 'w')
outp.write(result)
outp.close()
You can use the below command for the required output without any complex statement.
awk -f test.awk file.txt
test.awk must contains the below lines:
{
if(a=match($0,"\\["))
{
start=strtonum(substr($0,a+1,1));
end=strtonum(substr($0,a+3,1));
copy=$0;
for(i=start;i<=end;i++)
{
sub("\\[[0-9]{1,}-[0-9]{1,}\\]",i,copy);
print copy;
copy = $0;
}
}
else
{
print $0;
}
}
file.txt contains your input file like below lines:
app-server-l11[2-5].test.com
server-l34[5-8].test.com
dd-server-l[2-4].test.com
output:
app-server-l112.test.com
app-server-l113.test.com
app-server-l114.test.com
app-server-l115.test.com
server-l345.test.com
server-l346.test.com
server-l347.test.com
server-l348.test.com
dd-server-l2.test.com
dd-server-l3.test.com
dd-server-l4.test.com
As this sounds like a school assignment I'm going to be fairly vague.
I would use a regular expression to extract the numeric range and the rest of the address components, then use a loop to iterate over the extracted numeric range to build each address (using the other captured address components).
Since it's been over a week:
import re
inputs = [ "app-server-l11[2-5].test.com", "server-l34[5-8].test.com", "dd-server-l[2-4].test.com" ]
pattern = r"\s*(?P<subdomain>[a-zA-Z0-9-_.]+)\[(?P<range_start>\d+)-(?P<range_end>\d+)\](?P<domain>\S+)"
expr = re.compile( pattern )
def expand_domain( domain ):
mo = expr.match( domain )
if mo is not None:
groups = mo.groupdict()
subdomain = groups[ "subdomain" ]
domain = groups[ "domain" ]
range_start = int( groups[ "range_start" ] )
range_end = int( groups[ "range_end" ] )
result = [ "{}{:d}{}".format( subdomain, index, domain ) for index in range( range_start, range_end + 1 ) ]
return result
else:
raise ValueError( "'{}' does not match the expected input.".format( domain ) )
for domain in inputs:
print( "'{}':".format( domain ) )
for exp_dom in expand_domain( domain ):
print( "--> {}".format( exp_dom ) )

Rewrite c++ text encoder to python

I have the following code in c++:
for(const char *x = r.ptr, *end = r.ptr + r.len; x != end; ++x) {
switch(*x) {
case 0x5c:
case 0x22:
pc->output[0] = '\\'; pc->output[1] = *x; pc->output += 2;
break;
case 0xa:
pc->output[0] = '\\'; pc->output[1] = 'n'; pc->output += 2;
break;
case 0xd:
pc->output[0] = '\\'; pc->output[1] = 'r'; pc->output += 2;
break;
default:
if(str_escape_2_hex(*x)) {
impl::escape_char_hex(pc->output, *x);
} else {
*pc->output = *x; pc->output++;
}
}
}
And I want to rewrite it to python 2 because I need the same encoder there. I tried with this:
def encode_akv_fields(data):
hexlify = codecs.getencoder('hex')
for i, el in enumerate(str(data)):
if hexlify(el)[0] in ('5c', '22'): # \\ or "
data[i].encode('hex') = '\\' + hexlify(el)[0]
elif hexlify(el)[0] == '0a': # \n
data[i].encode('hex') = '\\n'
elif hexlify(el)[0] == '0d': # \r
data[i].encode('hex') = '\\r'
elif '1f' >= hexlify(el)[0] >= '7f':
tmp3 = (hexlify(el)[0] >> 4) & '0f'.decode('hex')
data[i].encode('hex') = '\\x'
return data
but it doesn't work - I got
SyntaxError: can't assign to function call
Data is a string or dict with values that I want to log. Those logs needs to be in AKV format (Apache key value). And for this to work I need some hex values to be encoded like it is in c++ (the code in c++ works).
How should I create the same encoder in python as I did in c++?

Get correct brace grouping from string

I have files with incorrect JSON that I want to start fixing by getting it into properly grouped chunks.
The brace grouping {{ {} {} } } {{}} {{{}}} should already be correct
How can I grab all the top-level braces, correctly grouped, as separate strings?
If you don't want to install any extra modules simple function will do:
def top_level(s):
depth = 0
start = -1
for i, c in enumerate(s):
if c == '{':
if depth == 0:
start = i
depth += 1
elif c == '}' and depth:
depth -= 1
if depth == 0:
yield s[start:i+1]
print(list(top_level('{{ {} {} } } {{}} {{{}}}')))
Output:
['{{ {} {} } }', '{{}}', '{{{}}}']
It will skip invalid braces but could be easily modified to report an error when they are spotted.
Using the regex module:
In [1]: import regex
In [2]: braces = regex.compile(r"\{(?:[^{}]++|(?R))*\}")
In [3]: braces.findall("{{ {} {} } } {{}} {{{}}}")
Out[3]: ['{{ {} {} } }', '{{}}', '{{{}}}']
pyparsing can be really helpful here. It will handle pathological cases where you have braces inside strings, etc. It might be a little tricky to do all of this work yourself, but fortunately, somebody (the author of the library) has already done the hard stuff for us.... I'll reproduce the code here to prevent link-rot:
# jsonParser.py
#
# Implementation of a simple JSON parser, returning a hierarchical
# ParseResults object support both list- and dict-style data access.
#
# Copyright 2006, by Paul McGuire
#
# Updated 8 Jan 2007 - fixed dict grouping bug, and made elements and
# members optional in array and object collections
#
json_bnf = """
object
{ members }
{}
members
string : value
members , string : value
array
[ elements ]
[]
elements
value
elements , value
value
string
number
object
array
true
false
null
"""
from pyparsing import *
TRUE = Keyword("true").setParseAction( replaceWith(True) )
FALSE = Keyword("false").setParseAction( replaceWith(False) )
NULL = Keyword("null").setParseAction( replaceWith(None) )
jsonString = dblQuotedString.setParseAction( removeQuotes )
jsonNumber = Combine( Optional('-') + ( '0' | Word('123456789',nums) ) +
Optional( '.' + Word(nums) ) +
Optional( Word('eE',exact=1) + Word(nums+'+-',nums) ) )
jsonObject = Forward()
jsonValue = Forward()
jsonElements = delimitedList( jsonValue )
jsonArray = Group(Suppress('[') + Optional(jsonElements) + Suppress(']') )
jsonValue << ( jsonString | jsonNumber | Group(jsonObject) | jsonArray | TRUE | FALSE | NULL )
memberDef = Group( jsonString + Suppress(':') + jsonValue )
jsonMembers = delimitedList( memberDef )
jsonObject << Dict( Suppress('{') + Optional(jsonMembers) + Suppress('}') )
jsonComment = cppStyleComment
jsonObject.ignore( jsonComment )
def convertNumbers(s,l,toks):
n = toks[0]
try:
return int(n)
except ValueError, ve:
return float(n)
jsonNumber.setParseAction( convertNumbers )
Phew! That's a lot ... Now how do we use it? The general strategy here will be to scan the string for matches and then slice those matches out of the original string. Each scan result is a tuple of the form (lex-tokens, start_index, stop_index). For our use, we don't care about the lex-tokens, just the start and stop. We could do: string[result[1], result[2]] and it would work. We can also do string[slice(*result[1:])] -- Take your pick.
results = jsonObject.scanString(testdata)
for result in results:
print '*' * 80
print testdata[slice(*result[1:])]

Categories