Python 2.7 - Converting a single character string to an integer - python

I'm trying to make a program which reads from two text file line by line and stores the line which you have specified in Name_Input earlier (in variable line and line 2), it then strips off anything which is not a number from the string.
for line in Roster_Inputed:
if Name_Input in line:
line = re.sub('[^0-20]', '', line)
if line == "1":
print(Name_Input + " " + "should have " + line + " " + "ally.")
print " "
else:
print(Name_Input + " " + "should have " + line + " " + "allies.")
print " "
for line2 in Roster_Should_Have:
if Name_Input in line2:
line2 = re.sub('[^0-20]', '', line2)
if line2 == "1":
print(Name_Input + " " + "actually has " + line2 + " " + "ally.")
print " "
else:
print(Name_Input + " " + "actually has " + line2 + " " + "allies.")
print " "
The code reads from two files which contain names and number after a space, it then goes on to compare them to determine what it outputs to the user:
if line == line2:
print "All good"
elif line != line2:
print "Check " + Name_Input + "'s " + "spies"
print " "
What I need it to do is check if the value of "line" is greater than "line2" however I cannot do so because they are strings which contain numbers. Is there a way to temporarily convert them to integers?

You can use chr() and ord() functions:
>>> chr(97)
'a'
>>> ord('a')
97
Hope it helps.

What about calling int?
>>> int('345')
345

Since I have now gotten confirmation that the characters will always be integers and the integers are what you want to compare, I can now say use int():
>>> int('4')
4
In your case, if int(line) > int(line2): should do what you want. Since files usually have new-line characters at the end of each line, you should probably consider using int(line.strip()) and int(line2.strip()).

Related

How do I loop a piece of code (have tried for, doesn't seem to work for me) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I'm looking for a way to loop the code below... so that it'll go through and print the first sentence, then the second sentence over and over until one entity's health drops to zero.
From my research (bearing in mind I'm a knucklehead) the 'for' function seems to only work with single words/numbers... but perhaps I'm wrong.
CODE:
if sentence == 1:
print ("The" + " " + enemy_1 + " " + random.choice(attack_verb) + " " + main_character + " " + "with its" + " " + random.choice(enemy_1_weapon))
enemy_1_health -= 20
print (enemy_1_health)
sentence = 0
if sentence == 0:
print (main_character + " " + random.choice(attack_verb) + " " + "the" + " " + enemy_1 + " " + "with his" + " " + random.choice(main_character_weapon))
enemy_1_health -= 20
print (enemy_1_health)
sentence = 1
#And then repeat and repeat over and over :)
you could do something like this
while enemy_1_health > 0:
if sentence == 1:
print ("The" + " " + enemy_1 + " " + random.choice(attack_verb) + " " + main_character + " " + "with its" + " " + random.choice(enemy_1_weapon))
enemy_1_health -= 20
print(enemy_1_health)
sentence = 0
if sentence == 0:
print (main_character + " " + random.choice(attack_verb) + " " + "the" + " " + enemy_1 + " " + "with his" + " " + random.choice(main_character_weapon))
enemy_1_health -= 20
print(enemy_1_health)
sentence = 1
Since you want the loop to happen while a particular condition is true, rather than for each item in a list/range/etc, you want a while loop:
while enemy_1_health > 0:
print(f"The {enemy_1} {random.choice(attack_verb)} {main_character} with its {random.choice(enemy_1_weapon)}")
enemy_1_health -= 20
print(enemy_1_health)
print(f"{main_character} {random.choice(attack_verb)} the {enemy_1} with his {random.choice(main_character_weapon)}")
enemy_1_health -= 20
print(enemy_1_health)
Note that you don't need the if sentence stuff because you're always setting sentence in such a way as to make it equivalent to if True, at which point you can dispense with the whole thing.
Here's an example of how you could use a for loop to iterate over the different attack scenarios:
while enemy_1_health > 0:
for attacker, attacker_pronoun, victim, weapons in [
(f"The {enemy_1}", "its", main_character, enemy_1_weapon),
(main_character, "his", f"the {enemy_1}", main_character_weapon),
]:
print(f"{attacker} {random.choice(attack_verb)} {victim} with {attacker_pronoun} {random.choice(weapons)}")
enemy_1_health -= 20
print(enemy_1_health)

Anagram program with sentences

I have a question about the following code:
str1 = "Race"
str2 = "Care"
# convert both the strings into lowercase
str1 = str1.lower()
str2 = str2.lower()
# check if length is same
if(len(str1) == len(str2)):
# sort the strings
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)
# if sorted char arrays are same
if(sorted_str1 == sorted_str2):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
"Race" and "Care" are now anagrams, but how to make an anagram with sentences?
For example:
str1 = "Race is good"
str2 = "Careisgood"
They are also an anagram, but it gives that it is not an anagram. I think it's because of the spaces. How to skip the spaces?
To remove spaces from a string, you can use the replace(" ", "") method.
str1 = "Race is good"
str2 = "Careisgood"
# convert both the strings into lowercase
str1 = str1.lower().replace(" ", "")
str2 = str2.lower().replace(" ", "")
# check if length is same
if(len(str1) == len(str2)):
# sort the strings
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)
# if sorted char arrays are same
if(sorted_str1 == sorted_str2):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")

Python: TypeError: can only concatenate str (not "int") to str : variable stored wrong

Hi Need clarification for python variable stored as wrong value , here is code :
userinput1 = int(input('enter start value\n'))
userinput2 = int(input('enter stop value\n'))
userinput3 = int(input('enter rampup time in seconds\n'))
userinput4 = float(input('enter increments delta \n'))
userinput5 = input('Enter sequence channels: A A A A or D D D D - A Ascend, D Descent , E Exclude \n')
command1 = "RAMP " + str(userinput5) + " " + userinput1 + " " + userinput2 + " " + userinput4 + " " + userinput3
port.write(command1.encode())
#### ERROR #####
command1 = str("RAMP " + str(userinput5) + " " + userinput1 + " " + userinput2 + " " + userinput4 + " " + userinput3)
TypeError: can only concatenate str (not "int") to str
Can you please clarify me correct method to store both type variable input in single variable command. type caste was done already.
You can concate only strings, so before concate all your userinputs you must "convert" them into strings
Example1:
command1 = "RAMP " + " ".join(map(str, [userinput5, userinput1, userinput2, userinput4, userinput3]))
Example2:
command1 = f"RAMP {userinput5} {userinput1} {userinput2} {userinput4} {userinput3}"

Python skipping elif statement

I'm trying to write a program that prints the values and keys in a dictionary depending of the input the user types. The problem appears when the elif statement on line 11 gets skipped. It doesn't matter if the if statement is false, the elif statement gets skipped. I'm learning so I don't really know where my error is. Thanks for the help!
areaM = {str(1) + " acre" : str(160) + " sq rods"}
linearM = {str(1) + " ft" : str(12) + " in", str(1) + " yd": str(3) + " ft"}
def displayConversion(conv):
for k, v in conv.items():
print(str(v) + " = " + str(k))
while True:
print("Enter a conversion")
if input() == "Area Meassure":
displayConversion(areaM)
elif input() == "Linear Meassure":
displayConversion(linearM)
else:
print("Conversion not available")
Maybe this as the full code (too much inputss):
areaM = {str(1) + " acre" : str(160) + " sq rods"}
linearM = {str(1) + " ft" : str(12) + " in", str(1) + " yd": str(3) + " ft"}
def displayConversion(conv):
for k, v in conv.items():
print(str(v) + " = " + str(k))
while True:
a=input("Enter a conversion\n")
if a == "Area Meassure":
displayConversion(areaM)
break
elif a == "Linear Meassure":
displayConversion(linearM)
break
else:
print("Conversion not available")

Remove trailing white space in python 3

Having bit of trouble with a program i made. i am getting it to display a diamond but i have a problem, here is my code:
a = input("Enter width: ")
a = int(a)
b = a
for i in range(a):
i = i + 1
b = a - i
text = " " * b + " " + "* " * i
print(text[:-1])
for i in range(a):
i = i + 1
b = a - i
text = " " * i + " " + "* " * b
print(text[:-1])
Thanks for all the help! this is the answer
That's because print doesn't return the string, it returns None.
>>> print(print("foo"))
foo
None
Perhaps you wanted to do this:
text = " " * i + " " + "* " * b
print (text[:-1])
To remove the trailing white-space better use str.rstrip:
>>> "foo ".rstrip()
'foo'
help on str.rstrip:
>>> print (str.rstrip.__doc__)
S.rstrip([chars]) -> str
Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
You can write your slice like this (not on the print return value):
("* "*b)[:-1]
or, you can use join:
' '.join(['*']*b)

Categories