File Inout Output multiple delimiters - python

i am trying to construct a dictionary based on a file that is seperated by different delimiters. For example i the file im reading is structured the following way, i need the line as a variable for demonstrative purposes
g = "ENGL 1301,preprofessional,MATH 2413,"
if ","and "," in g :
print "yay"
if "," and "," and "," in g:
print "nay"
the file can have multiple commas which means different things so im trying to diffinterate between the amount of commas in the line. I want the above program to only print "nay" since there are 3 commas in the string and not 2. How can i accomplish this since the above program failed and printed both "yay" and "nay"

Use str.count:
g = "ENGL 1301,preprofessional,MATH 2413,"
commas = g.count(",") # I put this up here so it isn't called multiple times
if commas == 2:
print "yay"
elif commas == 3: # I used `elif` here since `commas` cannot equal 2 and 3
print "nay"
Also, your current code doesn't work because non-empty strings evaluate to True in Python. So, this:
if "," and "," in g :
print "yay"
if "," and "," and "," in g:
print "nay"
becomes like this:
if True and ("," in g):
print "yay"
if True and True and ("," in g):
print "nay"
As you can guess, each of those if-statements will always pass.

Related

Replacing The Tab Character In A String

Let's say I have a string like this:
a = a = "\t\t\t\t"
If I print out the count of "\t" in the string, this is the output:
print(a.count("\t")) == output = 4 \
If I wanted to replace "\t" at any given occurrence in that string, how would I do it?
ex:
a.replace("\t", "a") #replacing the (first occurrence?) of "\t?
print(a.count("\t")) == output = 3
However, the "\t" is not getting replaced by "a" and therefore the "\t" count is still 4. Is there a way I can do this; preferably replace any given occurrence of "\t" within the string?
You can use regular expressions. It is another way to replace all the occurencies by specific pattern
try to use expandtabs, such as text = text.expandtabs(tabsize=4)
As Michael Butscher says, str.replace() returns a new string with replacements done. By default, all occurrences are replaced. Tabs are not a special case. This should do it:
a = a.replace("\t", "a")
print(a.count("\t"))
See: https://docs.python.org/3/library/stdtypes.html?highlight=str%20replace#str.replace
Thank you for the responses as they really opened the door to the solution. What I have done is converted a into a list:
a = "\t\t\t\t"
b = a.list()
#print(b):
#['\t', '\t', '\t', '\t']
I can then just use indices to replace what I need b[0] = "a", and then just convert it back into a str when I am done. This suits my purpose, but there are multiple ways of dealing with it like if I wanted to change all the "\t" into a "a" I could do a simple iteration like this:
for x in range(0, len(b)):
if b[x] == "\t":
b[x] = "a"
Of course the replace() function could do the same with it in string format, but at least with this iteration I could add more conditional logic if needed.

Two if statements on same line

Very new to this, and cant seem to get these two to print on the same line. Python 3
isCold= sys.argv[1] == 'True'
isRainy= sys.argv[2] == 'True'
if isCold:
print "cold and",
else:
print "warm and ",
if isRainy:
print('rainy')
else:
print('dry')
Keep getting:
cold and
rainy
I need:
cold and rainy
print has an end parameter whose default value is \n, a newline. Call the first prints with print("cold and", end="") and they won't skip to the next line.
on the end of each print statement there is a \n which means "enter" or "new line"
build your str with + signs and print the build-up string at the end.
Each call to print will result in the text being printed on its own line because a new line character is appended. This is mentioned in the documentation -
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
The default value for end is why you are seeing a new line after each call to print.
What you could do is build a string variable in your conditional statements and then only print once at the end -
output = ''
if isCold:
output += "cold and"
else:
output += "warm and "
if isRainy:
output += 'rainy'
else:
output += 'dry'
print output
In addition, I see you are assigning string values instead of boolean values. In python "True" is not the same as True. You should assign proper boolean values. Take the following example -
myBool = 'True'
if myBool:
print('Bool is truthy')
myBool = 'False'
if myBool:
print('Bool is STILL truthy')
myBool = False
if myBool:
print('This should not be printed')
The print() function in Python takes more than one argument. One of the arguments is the end.
Now usually, the print function has a default argument of end="\n", where \n is newline. This is the reason why your output comes as:
cold and
rainy - instead of:
cold and rainy
One solution to the many is to specify end. The end determines what the printed string will end with. For example:
>>> print("It is raining", end="!")
It is raining!
>>> print("What", end=",")
What,
So to get your output on the same line, you can try the following:
print("cold and", end="")
This will override the default argument of '\n' and you will get the desired output.
Rather than two print calls, you can create a single string and print once.
Consider:
print("{} and {}".format(("warm", "cold")[isCold], ("dry", "rainy")[isRainy]))
In this case you are using the boolean value of each iCold and isRainy to index a tuple of strings to create a single string with all combinations.
You can also use the Python ternary to accomplish the same:
print("{} and {}".format("cold" if isCold else "warm", "rainy" if isRainy else "dry"))
You can also try this:
if isCold:
a = "cold and "
else:
b = "warm and "
if isRainy:
print(a+'rainy')
else:
print(b+'dry')
Use a logical and:
if sys.argv[1] == 'True' and sys.argv[2] == 'True':
print("cold and rainy)

Python: Remove words from a given string

I'm quite new to programming (and this is my first post to stackoverflow) however am finding this problem quite difficult. I am supposed to remove a given string in this case (WUB) and replace it with a space. For example: song_decoder(WUBWUBAWUBWUBWUBBWUBC) would give the output: A B C. From other questions on this forums I was able to establish that I need to replace "WUB" and to remove whitespace use a split/join. Here is my code:
def song_decoder(song):
song.replace("WUB", " ")
return " ".join(song.split())
I am not sure where I am going wrong with this as I the error of WUB should be replaced by 1 space: 'AWUBBWUBC' should equal 'A B C' after running the code. Any help or pointing me in the right direction would be appreciated.
You're close! str.replace() does not work "in-place"; it returns a new string that has had the requested replacement performed on it.
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Do this instead:
def song_decoder(song):
song = song.replace("WUB", " ")
return " ".join(song.split())
For example:
In [14]: song_decoder("BWUBWUBFF")
Out[14]: 'B FF'
Strings are immutable in Python. So changing a string (like you try to do with the "replace" function) does not change your variable "song". It rather creates a new string which you immediately throw away by not assigning it to something. You could do
def song_decoder(song):
result = song.replace("WUB", " ") # replace "WUB" with " "
result = result.split() # split string at whitespaces producing a list
result = " ".join(result) # create string by concatenating list elements around " "s
return result
or, to make it shorter (one could also call it less readable) you can
def song_decoder(song):
return " ".join(song.replace("WUB", " ").split())
Do the both steps in a single line.
def song_decoder(song):
return ' '.join(song.replace('WUB',' ').split())
Result
In [95]: song_decoder("WUBWUBAWUBWUBWUBBWUBC")
Out[95]: 'A B C'

exec with ';' in python

I am creating a string, to print the fields in a list, . the fields should be separated by ';', code snippet looks like this( simplified code, not actual )
list = ["abc","xyz","pqr"]
str = "print " + "list[0]" + ";" + "list[2]" # This is dynamically generated
exec (str)
My problem here is, with exec statement, it prints only "xyz" , because of the semi colon. what is the best way to solve this, so that the exec statement prints "xyz;pqr"
You are generating the following code:
print list[0];list[2]
Note that the ; is not quoted. Since a ; is used by Python to separate multiple simple statements on a line, Python executes the print list[0] first, then list[2] (which ends up doing nothing).
You'd have to generate this code instead:
print list[0] + ';' + list[2]
which you could do with:
str = "print " + "list[0]" + " + ';' + " + "list[2]"
However, you should not be using code generation at all. Use standard Python methods to join or format a string. You could use str.format():
print '{};{}'.format(list[0], list[2])
or you could use str.join():
print ';'.join([list[0], list[2]])
If you must vary what code is executed based on some other variables, try to avoid exec still. You could use from __future__ import print_function or encapsulate the print statement in a new function, then call functions dynamically. You can always use a dispatch table to map a string to a function to call, for example.
Try this:
str = "print" + "list[0]" + "';'" + "list[2]"
or
str = "print" + "list[0]" + "/;" + "list[2]"
The problem here is that Python optionally allows semicolons to delimit two separate statements (Compound statements). So when you use exec on the evaluated statement print "abc";"xyz", Python thinks they are two separate statements, hence, only printing "abc".
You could use single quotes around the semicolon to show that it is a string and concatenate them with their surrounding strings:
# Refrain from using list and str as they are built-ins
l = ["abc", "xyz", "pqr"]
s = "print " + "l[0]" + "+';'+" + "l[2]"
exec(s)

Why does my code print twice the amount of spaces I expect?

Python provides a built-in function called len that returns the length of a string, so the value of len('allen') is 5. Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.
Author's solution:
def right_justify(s):
print (' '*(70-len(s))+s)
>>> right_justify('allen')
My solution:
def right_justify(s):
space_count=70-len(s)
for i in range(0,space_count,1):
print " ",
print s
strng=raw_input("Enter your desired string:")
print len(strng)
right_justify(strng)
The output of my code is different than the output of author's code: I am getting twice as many spaces, e.g. 130 instead of 65.
But it seems to me that the two pieces of code are logically equivalent. What am I overlooking?
The problem is with your print statement
print " ",
will print two spaces for each iteration of the loop. When terminating the print statement with a comma, subsequent calls will be delimited by a space.
On a side note, another way to define your right_justify function would be
def right_justify(s):
print '%70s' % s
The print " ", line actually prints two spaces (one from the " ", one from the ,). You could replace it with print "", to have your function work identically to the original.
Your code has 130 spaces, the author's code has 65 spaces. This is because
print " ",
...adds a space. What you want is:
print "",
I would prefer the function str.rjust(70," ") which does the trick, I think, like so:
strng.rjust(70," ")

Categories

Resources