Converting a Range to display as a String - python-3.x

New python user here;
Write a program that reads a single line of text as input and outputs only the first, third, fifth... letter of the string.
I have trouble converting the range to display as a string
My Code:
user = str(input("Please enter a string: "))
for x in user:
if range(0,user,2) :
print(str(user))

You can read input as string and use a loop that runs from 0 till length of the string, incremented by 2. Then you can print the value at each position.
You can find length of a string with len() like this
length = len(string)
Your code can be edited like shown below
user = str(input("Please enter a string: "))
for i in range(0, len(user), 2):
print(user[i], end=' ')
Output
# Let input = abcdefghi
a c e g i
Hope this helps.!!

Related

Trying to convert each x'th character to Uppercase

So basically my homework consists of making a program that asks for a string and an integer 'x'.'x' is basically the step in this program. First it converts the whole string to lowercase and then each 'x'th' character of the string must be converted to uppercase. So if i input "Hello World" and my integer is 1. Output would be "hElLo wOrLd". Im new to python by the way.
This is what ive got right now and im basically stuck in a loop of trying a 100 things:
s = input('Input a string: ')
g = input('Input an integer: ')
s = s.lower() #converts the whole string ofc
s = list(s)
range1 = s[::g]
range1 = range1.upper()
print(s)
First, convert g to an int because input returns a str and you can't slice a list with a str, also, s[::g] (which should be s[g::g + 1]) is an independent sublist of s, and it has no reference to s, so assigning it to range1 and modifying it will not modify s, and one more note, s[::g] is a list, and you should call str.upper on its elements, not on it itself, you can use map for this:
s = list(input('Input a string: ').lower())
g = int(input('Input an integer: '))
s[g::g + 1] = map(str.upper, s[g::g + 1])
s = ''.join(s)
print(s)
Input:
Input a string: Hello World
Input an integer: 1
Output:
hElLo wOrLd

How to fix eror base 10 when emty or not integer input in loop

I'm creating simple multiplication program and i stuck at empty and non integer input
I tried while loop in loop and if/else but because the input is coming first it shows the error and breaks the program
while g < 20 :
variable_1 = random.randint (0,20)
variable_2 = random.randint (0,9)
answer = variable_1 * variable_2
querystr = int(input("str(variable_1)+" x "+str(variable_2)+" = "))
program works fine with multiplication for any integer input if answer is correct or incorrect. problem is that should discard empty input and when entered a letter should be terminate.
Try to first get the data from the user without casting it to an integer, then test the input to decide what to do.
The following example will wait until an input will be entered:
querystr = ''
while not querystr:
querystr = input('What do you have to say?')
Now, if you want to break the loop if a letter is entered (when you expect only integers) you can try something like that:
import string
expected_int = ''
while not expected_int:
try:
expected_int = input('Insert an integer or a letter to exist:')
if no expected_int:
continue
if expected_int in string.ascii_letters:
break
expected_int = int(expected_int)
except:
pass

Extracting Certain Numbers From an Int Value

i am trying to get the numbers in individual form added to a list.
For example, if i input 3245, i want the list to say
["3","2","4","5"]
I have tried using a for in statement but got back numbers ranging from 0 - 3244 which was expected.
Any insight would be greatly appreciated, i am very new to python and am trying to teach myself code and re-write all my projects for school that was done in c to turn them into python. NOTE: i am using python 3, not 2.
Here is the rest of my code if it helps.
cc = []
card = int(input("Credit Card: "))
for n in range(card):
cc.append(n)
print(cc)
First of all, you should either accept the input number as string or convert it to string. That way, you can just parse through each character in the string and add them to the list. Currently you are getting the number 0-3244 because of you are looping for the amount of inputted number and adding the loop index to your list. Therefore, this should do what you want
cc = []
card = input("Credit Card: ") # or str(int(input("Credit Card: ")))
# if you want to restrict it to integer
for n in range(len(card)): # loop by number of characters
cc.append(card[n]) # append each character
print(cc)
a = 3245
b = list(str(a))
print(b)
The above code can convert an integer to a list of characters. First convert the integer to a string and then convert the string to a list form.
you can just convert the integer to string and iterate through every character of the string and during the iteration just append to cc.
cc = []
card = int(input("Credit Card: "))
for i in str(card):
cc.append(i)
print(cc)

hello friends i cant execute my else condition

The program must accept a string S as the input. The program must replace every vowel in the string S by the next consonant (alphabetical order) and replace every consonant in the string S by the next vowel (alphabetical order). Finally, the program must print the modified string as the output.
s=input()
z=[let for let in s]
alpa="abcdefghijklmnopqrstuvwxyz"
a=[let for let in alpa]
v="aeiou"
vow=[let for let in v]
for let in z:
if(let=="a"or let=="e" or let=="i" or let=="o" or let=="u"):
index=a.index(let)+1
if index!="a"or index!="e"or index!="i"or index!="o"or index!="u":
print(a[index],end="")
else:
for let in alpa:
ind=alpa.index(let)
i=ind+1
if(i=="a"or i=="e" or i=="i"or i=="o"or i=="u"):
print(i,end="")
the output is :
i/p orange
pbf
the required output is:
i/p orange
puboif
I would do it like this:
import string
def dumb_encrypt(text, vowels='aeiou'):
result = ''
for char in text:
i = string.ascii_letters.index(char)
if char.lower() in vowels:
result += string.ascii_letters[(i + 1) % len(string.ascii_letters)]
else:
c = 'a'
for c in vowels:
if string.ascii_letters.index(c) > i:
break
result += c
return result
print(dumb_encrypt('orange'))
# puboif
Basically, I would use string.ascii_letters, instead of defining that anew. Also, I would not convert all to list as it is not necessary for looping through. The consonants you got right. The vowels, I would just do an uncertain search for the next valid consonant. If the search, fails it sticks back to default a value.
Here I use groupby to split the alphabet into runs of vowels and consonants. I then create a mapping of letters to the next letter of the other type (ignoring the final consonants in the alphabet). I then use str.maketrans to build a translation table I can pass to str.translate to convert the string.
from itertools import groupby
from string import ascii_lowercase as letters
vowels = "aeiou"
is_vowel = vowels.__contains__
partitions = [list(g) for k, g in groupby(letters, is_vowel)]
mapping = {}
for curr_letters, next_letters in zip(partitions, partitions[1:]):
for letter in curr_letters:
mapping[letter] = next_letters[0]
table = str.maketrans(mapping)
"orange".translate(table)
# 'puboif'

How can I put user input into a list using eval?

thanks for helping.
I am having trouble with the following code:
digitsList = input("Enter any list of 0 or more digits in the form [digit, digit, ...]:")
if element == int(list[index]):
index += 1
return True
else:
index += 1
return False
for example the user entered : [1,2,3]
then I get a following error :
ValueError: invalid literal for int() with base 10: '['
I tried everything I can but not being able to solve it.
It's a bit difficult to read your code the way you posted it, but user input could be put into a list using the .append feature.
For example:
list = digitsList.append("what the user inputs goes here")
You are giving a wrong input. The input entered by the user should be like this in a single line : 1 2 3. If you are supposed to take a list as input, do this :
digitslist = map(int, raw_input("Enter any list of 0 or more digits in the form [digit, digit, ...]:").split())
Input : 1 2 3
Output : [1, 2, 3]
The input() function is supposed to take only one int, float or string entered with quotes as input.
Use following code:
x = [i for i in eval(input("Enter comma seperated"))]

Resources