Simplifying lists in python? [duplicate] - python

This question already has answers here:
Check if multiple strings exist in another string
(17 answers)
Closed 5 years ago.
I'm new to coding, and am wondering if there is a way to simplify this:
if "!" in name or "$" in name or "%" in name or "^" in name or "&" in name or "*" in name or "(" in name or ")" in name or "_" in name or "-" in name or "+" in name or "=" in name:
points = points + 1
Thank you

You can use regex:
import re
if re.findall('[\!\$\%\^\&\*\_\-\+\=]', name):
points += 1

chars = set("!$%^&*()_-+=")
if any((i in chars) for i in string):
points += 1

You can write a simple function to achieve this.
def is_included(characters, sentence):
for character in characters:
if character in sentence:
return True
return False
As mgilson mention you can use any keyword too. However since you are new to programming I suggest you to learn the algorithms of keywords.

Related

python string remove without using internal function [duplicate]

This question already has answers here:
Removing space in a string without using built in methods
(4 answers)
How to print without a newline or space
(26 answers)
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 4 months ago.
I'm a freshman CS student. This is one of the exercises we had in class:
Create a function called remove_space(string):
The function takes in a string as input
The function returns a new string, which is generated by removing all the spaces in the given string.
Example: remove_space(“welcome to computer science”) returns “welcometocomputerscience”
I have looked around for solutions online but we aren't allowed to use any advanced functions like split(), replace(), join() or anything of that sort. I'm looking for the most primitive way to solve this without using those that would make sense coming from a freshman CS student.
This is what I have so far:
def remove_space(string):
temp = ""
for char in string:
if char == " ":
char = temp
print(char)
print("----------------#1---------------")
remove_space("Welcome to computer science")
What am I doing wrong?
def remove_space(string):
result_string = ''
for character in string:
if character != ' ':
result_string += character
return result_string
remove_space('welcome to computer science')
Result:
'welcometocomputerscience'
Try this:
Create a variable temp, concat the char if it is != " " and then return temp
def remove_space(string):
temp = ""
for char in string:
if char != " ":
temp += char
return temp
print(remove_space("welcome to computer science"))
Simple answer:
When you write char = temp, you are basically assigning the variable to a new value instead of overriding t in the original string.
What you are doing is equivalent to:
a = 3
b = a
b = 2
Even though you tell b to be equal a, you reassign it later to be 2. If you print(a) you will see that its value will still be the same.
CS-Dojo has a great video on this https://youtu.be/Z1Yd7upQsXY?t=1002 you can start at minute 16 where he explains variable assignment.

Python : How to check if a variable is equal to '' '' [duplicate]

This question already has answers here:
Check if string contains only whitespace
(11 answers)
Closed 4 years ago.
I have a variable:
exchange_name = ''
Now I want to perform some operation based on checking if it is equal to an empty string.
So, I do:
if exchange_name == '':
# perform some operation
But how can I generalize the solution so that exchange_name can contain any number of spaces, e.g.:
exchange_name = ' '
or
exchange_name = ' '
Can anybody suggest an approach? Thanks in advance.
exchange_name.strip()==''
strip removes all empty spaces.
Try to use rstrip to remove spaces from begin and end of string.
if mytext.rstrip() == '':
do_it()

Capitalize first letter ONLY of a string in Python [duplicate]

This question already has answers here:
Capitalize a string
(9 answers)
How can I capitalize the first letter of each word in a string?
(23 answers)
Closed 6 years ago.
I'm trying to write a single line statement that assigns the value of a string to a variable after having ONLY the first letter capitalized, and all other letters left unchanged.
Example, if the string being used were:
myString = 'tHatTimeIAteMyPANTS'
Then the statement should result in another variable such as myString2 equal to:
myString2 = 'THatTimeIAteMyPANTS'
Like this:
myString= myString[:1].upper() + myString[1:]
print myString
Like Barmar said, you can just capitalize the first character and concatenate it with the remainder of the string.
myString = 'tHatTimeIAteMyPANTS'
newString = "%s%s" % (myString[0].upper(), myString[1:])
print(newString) # THatTimeIAteMyPANTS

Python: What is the Best way to split a string of 9 characters into 3 characters each and join them using delimiters? [duplicate]

This question already has answers here:
How to iterate over a list in chunks
(39 answers)
Closed 8 years ago.
I have a string "111222333" inside a CSV file. I would like to convert this into something like "\111\222\333"
Currently my python code is :
refcode = "111222333"
returnstring = "\\" + refcode[:3] + "\\" + refcode[3:6] + "\\" + refcode[-3:] + "\\"
I know there must be a better way to do this. May I know what are the better ways to do the same thing. Please help.
You could use re for that:
import re
refcode = "111222333"
returnstring = '\\'.join(re.match('()(\S{3})(\S{3})(\S{3})()', refcode).groups())
Explanation:
You have a string of 9 characters (let's say they are not any kind of whitespace chatacters, so we could represent it with \S).
We create a matching regexp using it, so (\S{3}) is a group of three sequential non-space characters (like letters, numbers, exclamation marks etc.).
(\S{3})(\S{3})(\S{3}) are three groups with 3 characters in each one.
If we call .groups() on it, we'll have a tuple of the matched groups, just like that:
In [1]: re.match('(\S{3})(\S{3})(\S{3})', refcode).groups()
Out[1]: ('111', '222', '333')
If we join it using a \ string, we'll get a:
In [29]: print "\\".join(re.match('(\S{3})(\S{3})(\S{3})', refcode).groups())
111\222\333
But you want to add the backslashes on the both sides of the string as well!
So we could create an empty group - () - on the each side of the regular expression.

Python: Best practice for dynamically constructing regex [duplicate]

This question already has answers here:
Escaping regex string
(4 answers)
Closed 9 months ago.
I have a simple function to remove a "word" from some text:
def remove_word_from(word, text):
if not text or not word: return text
rec = re.compile(r'(^|\s)(' + word + ')($|\s)', re.IGNORECASE)
return rec.sub(r'\1\3', text, 1)
The problem, of course, is that if word contains characters such as "(" or ")" things break, and it generally seems unsafe to stick a random word in the middle of a regex.
What's best practice for handling cases like this? Is there a convenient, secure function I can call to escape "word" so it's safe to use?
You can use re.escape(word) to escape the word.
Unless you're forced to use regexps, couldn't you use instead the replace method for strings ?
text = text.replace(word, '')
This allows you to get rid of punctuation issues.
Write a sanitizer function and pass word through that first.
def sanitize(word):
def literalize(wd, escapee):
return wd.replace(escapee, "\\%s"%escapee)
return reduce(literalize, "()[]*?{}.+|", word)
def remove_word_from(word, text):
if not text or not word: return text
rec = re.compile(r'(^|\s)(' + sanitize(word) + ')($|\s)', re.IGNORECASE)
return rec.sub(r'\1\3', text, 1)

Categories

Resources