Trying to convert each x'th character to Uppercase - python-3.x

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

Related

Accessing strings from a array of strings in GNU Octave

How to access the whole elements hello and ahoy in Octave? Only the first character in each string is being printed.
octave:1> s = ["hello";"ahoy"]
s =
hello
ahoy
octave:2> s(1)
ans = h
octave:3> s(2)
ans = a
Use cell arrays instead.
octave:1> s = { 'hello'; 'ahoy' };
octave:2> s{1}
ans = hello
octave:3> s{2}
ans = ahoy
See https://octave.org/doc/v5.2.0/Cell-Arrays.html#Cell-Arrays
Check the size and type of s to understand what's going on:
octave:5> size(s)
ans =
2 5
octave:6> class(s)
ans = char
It's a 2x5 matrix of characters. To index, use matrix indexing. For example getting the first row:
octave:7> s(1,:)
ans = hello

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'

Converting a Range to display as a String

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.!!

python3 sum in stings each letter value

i need sum in string letters value ex.
a = 1
b = 2
c = 3
d = 4
alphabet = 'abcdefghijklmnopqrstuvwxyz'
v1
string = "abcd"
# #result = sum(string) so
if string[0] and string[1] and string[2] and string[3] in alphabet:
if string[0] is alphabet[0] and string[1] is alphabet[1] and string[2] is alphabet[2] and string[3] is alphabet[3]:
print(a+b+c+d)
v2
string = ("ab","aa","dc",)
if string[0][0] and string[0][1] and string[1][0] and string[1][1] and string[2][0] and string[2][1] in alphabet:
if string[0] is alphabet[0] and string[1] is alphabet[1] and string[2] is alphabet[2] and string[3] is alphabet[3]:
print(a+b+c+d)
what is the solution? can you help me
Use the sum() function and a generator expression; a dictionary built from string.ascii_lowercase can serve as a means to getting an integer value per letter:
from string import ascii_lowercase
letter_value = {c: i for i, c in enumerate(ascii_lowercase, 1)}
wordsum = sum(letter_value.get(c, 0) for c in word if c)
The enumerate(ascii_lowercase, 1) produces (index, letter) pairs when iterated over, starting at 1. That gives you (1, 'a'), (2, 'b'), etc. That can be converted to c: i letter pairs in a dictionary, mapping letter to integer number.
Next, using the dict.get() method lets you pick a default value; for any character in the input string, you get to look up the numeric value and map it to an integer, but if the character is not a lowercase letter, 0 is returned instead. The sum(...) part with the loop then simply adds those values up.
If you need to support sequences with words, just use sum() again. Put the above sum() call in a function, and apply that function to each word in a sequence:
from string import ascii_lowercase
letter_value = {c: i for i, c in enumerate(ascii_lowercase, 1)}
def sum_word(word):
return sum(letter_value.get(c, 0) for c in word if c)
def sum_words(words):
return sum(sum_word(word) for word in words)
The old-fashioned way is to take advantage of the fact that lowercase letters are contiguous, so that ord(b) - ord(a) == 1:
data = "abcd"
print("Sum:", sum(ord(c)-ord("a")+1 for c in data))
Of course you could "optimize" it to reduce the number of computations, though it seems silly in this case:
ord_a = ord("a")
print("Sum:", sum(ord(c)-ord_a for c in data)+len(data))

Combining two strings to form a new string

I am trying to write a program that asks the user for two strings and creates a new string by merging the two together (take one letter from each string at a time). I am not allowed to use slicing. If the user enters abcdef and xyzw, program should build the string: axbyczdwef
s1 = input("Enter a string: ")
s2 = input("Enter a string: ")
i = 0
print("The new string is: ",end='')
while i < len(s1):
print(s1[i] + s2[i],end='')
i += 1
The problem I am having is if one of the strings is longer than the other I get an index error.
You need to do your while i < min(len(s1), len(s2)), and then make sure to print out the remaining part of the string.
OR
while i < MAX(len(s1), len(s2)) and then only print s1[i] if len(s1) > i and only print s2[i] if len(s2) > i in your loop.
I think zip_longest in Python 3's itertools gives you the most elegant answer here:
import itertools
s1 = input("Enter a string: ")
s2 = input("Enter a string: ")
print("The new string is: {}".format(
''.join(i+j for i,j in itertools.zip_longest(s1, s2, fillvalue=''))))
Here's the docs, with what zip_longest is doing behind the scenes.

Resources