I'm trying to code a chatbot that will print a string containing n times the first letter of my name, followed by "n" and then followed by n-1 times the second letter in my name.
Example:
name: chris
n = 5 (since there are 5 letters in the name)
n-1 = 4
first letter of the name: c
second letter of the name: h
The string I want to generate: ccccc5hhhh
My problem: The string generated is in brackets which I don't want. I want the string to be exactly as "ccccc5hhhh", no spaces; all in one line, but I keep getting ['c','c','c','c','c']5['h','h','h','h'] as the output.
st1 = input("First name? ==> ")
print("Please enter the first letter of your name")
letter = input ("First letter? ==>? ")
if (letter == st1[0]):
# initializing list of lists
test_list = st1[0]
test_list1 = st1[1]
# repeat letters n times
res = [ele for ele in test_list for i in range(len(st1))]
res2 = [ele for ele in test_list1 for i in range(len(st1)-1)]
# printing result
print(str(res), len(st1), str(res2))
You are looking for the join function. Using , with your arguments will insert a space though.
To get the result you are looking for you will want:
print(''.join(res) + str(len(st1)) + ''.join(res2))
Instead of converting your lists into string you can use the .join() function, like so ''.join(res)
So you final line should be:
print(''.join(res) + str(len(st1)) + ''.join(res2))
You're overcomplicating this. Just use string multiplication.
s = 'chris'
n = len(s)
res1 = s[0] * n
res2 = s[1] * (n - 1)
print(res1 + str(n) + res2) # -> ccccc5hhhh
Related
I should create a program that will find the characters that are in alphabetical order in a given input and find how many characters are in that particular substring or substrings.
For example
Input: cabin
Output: abc, 3
Input: sightfulness
Output: ghi, 3
OUtput: stu, 3
Here is what I have coded so far. I am stuck in the part of checking whether the two consecutive letters in my sorted list is in alphabetical order.
I have converted that string input to a list of characters and removed the duplicates. I already sorted the updated list so far.
import string
a = input("Input A: ")
#sorted_a is the sorted letters of the string input a
sorted_a = sorted(a)
print(sorted_a)
#to remove the duplicate letters in sorted_a
#make a temporary list to contain the filtered elements
temp = []
for x in sorted_a:
if x not in temp:
temp.append(x)
#pass the temp list to sorted_a, sorted_a list updated
sorted_a = temp
joined_a = "".join(sorted_a)
print(sorted_a)
alphabet = list(string.ascii_letters)
print(alphabet)
def check_list_order(sorted_a):
in_order_list = []
for i in sorted_a:
if any((match := substring) in i for substring in alphabet):
print(match)
#this should be the part
#that i would compare the element
#in sorted_a with the elements in alphabet
#to know the order of both of them
#and to put them ordered characters
#to in_order_list
if ord(i)+1 == ord(i)+1:
in_order_list.append(i)
return in_order_list
print(check_list_order(sorted_a))
You could try something like this:
string = input("Input string: ")
chars = sorted(set(string.strip().casefold()))
parts, part = [], ""
for a, b in zip(chars, chars[1:] + ["-"]):
part += a
if ord(a) + 1 != ord(b):
if len(part) > 1:
parts.append(part)
part = ""
print(parts)
The result parts for the input-string "sightfulness" would be
['efghi', 'stu']
so I'm not quite sure why your output differs: Is there a requirement that you haven't mentioned?
If - could be part of the string then replace ... + ["-"] with something more suitable. If you want to exclude any characters that are not in the alphabet then you could do:
from string import ascii_lowercase as alphabet
string = input("Input string: ")
chars = sorted(set(string.strip().casefold()).intersection(alphabet))
...
I have a list here where I only need to input 10 letters or strings. I am having a problem separating the list.
print ("Please input letter: \n")
num_string = []
num = 10
for i in range (0,num):
element = str(input(str(i + 1) + ". "))
num_string.append(element)
string = ' '.join([str(item) for item in num_string])
print (string)
In my code, for example, I inputted a b c d e f g h i j since it is only 10 inputs. Instead of having an output like a b c d e f g h i j because I used the join method, I want to have a NewLine for every list. So I want it to be like
a
b
c
d
e
f
g
h
i
j
You are almost there just instead of joining a whitespace, join a newline, also you don't need to convert each element to string because each element is a string already because input always returns a string (in Python3) (so this is redundant: str(input()), it is the exact same as: input()):
string = '\n'.join(num_string)
Complete example (removed the redundant str):
print("Please input letter: \n")
num_string = []
num = 10
# the 0 isn't necessary either but
# I guess for clarification it can stay
for i in range(0, num):
element = input(str(i + 1) + ". ")
num_string.append(element)
string = '\n'.join(num_string)
print(string)
Alternatively you can use this (instead of the last two lines in the above code example):
print(*num_string, sep='\n')
And if you really want to shorten the code (it can be as short as 3 lines):
print("Please input letter: \n")
num = 10
print('\n'.join(input(f'{i + 1}. ') for i in range(num)))
print ("Please input letter: \n")
num_string = []
num = 10
for i in range (0,num):
element = str(input(str(i + 1) + ". "))
num_string.append(element)
string = '\n' .join([str(item) for item in num_string])
print (string)
Use '\n' , it is like a breakline in your output
str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
Like I want to extract I Love Python from this string. But I am not getting how to.
I tried to loop in str1 but not successful.
i = str1 .index("I")
for letter in range(i, len(mystery11)):
if letter != " ":
letter = letter+2
else:
letter = letter+3
print(mystery11[letter], end = "")
In your for loop letter is an integer. In the the first line of the loop you need to compare mystery[11] with " ":
if mystery11[letter] != " ":
You can use a dict here, and have char->freq mapping of the sentence in it and create a hash table.
After that you can simply iterate over the string and check if the character is present in the hash or not, and if it is present then check if its count is greater than 1 or not.
Don't know if this will solve all your problems, but you're running your loop over the indices of the string, This means that your variable letter is an integer not a char. Then, letter != " " is always true. To select the current letter you need to do string[letter]. For example,
if mystery11[letter] != " ":
...
Here's how I'd go about:
Understand the pattern of the input: words are separated by blank spaces and we should get every other letter after the first uppercase one.
Convert string into a list;
Find the first uppercase letter of each element and add one so we are indexing the next one;
Get every other char from each word;
Join the list back into a string;
Print :D
Here's the code:
def first_uppercase(str):
for i in range(0, len(str)):
if word[i].istitle():
return i
return -1
def decode_every_other(str, i):
return word[i::2]
str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
# 1
sentence = str1.split()
clean_sentence = []
for word in sentence:
# 2
start = first_uppercase(word) + 1
# 3
clean_sentence.append(decode_every_other(word, start))
# 4
clean_sentence = ' '.join(clean_sentence)
print("Input: " + str1)
print("Output: " + clean_sentence)
This is what I ended up with:
Input: srbGIE JLWokvQeR DPhyItWhYolnz
Output: I Love Python
I've added some links to the steps so you can read more if you want to.
def split(word):
return [char for char in word]
a = input("Enter the original string to match:- ")
b = input("Enter the string to lookup for:- ")
c = split(a)
d = split(b)
e = []
for i in c:
if i in d:
e.append(i)
if e == c:
final_string = "".join(e)
print("Congrats!! It's there and here it is:- ", final_string)
else:
print("Sorry, the string is not present there!!")
I intended to let the program check if the input matches with any character in a str and then print out the result, the player input and the underscores in the correct places. This is my test code so far:
astring = "apple"
bstring = "_ " * 5
print(bstring)
my_input = input("enter a letter")
for i, n in enumerate(astring):
if my_input == i:
bstring[n] = my_input
else:
i = i + 1
print(bstring)
However, only the underscores are being printed out. Can anyone help me?
In your loop, you should be checking to see if the letter at your current index of your string is the same as the letter at the current index of your input string, to do this you can use:
if i < len(my_input) and my_input[i] == n:
Also, strings in Python are immutable, and so you can't change them via index. Instead, use an array of _, so that you can change what is at a particular index. Then, at the end, join each element in your list by a space.
Lastly, there is no need to increment i, as this is done for you by your for loop:
astring='apple'
bstring=['_']*len(astring)
print(bstring)
my_input = input('enter a letter')
for i,n in enumerate(astring):
if i < len(my_input) and my_input[i] == n:
bstring[i] = n
print(' '.join(bstring))
for i,n in enumerate(astring):
'i' is the index, 'n' is the character. You have it the other way around in 'if'.
hope it will help you
astring='apple'
bstring=["_" for i in range(len(astring))]
print(bstring)
my_input=input('enter a letter')
for i,n in enumerate(astring):
if my_input==n:
bstring[i]=my_input
else:
i=i+1
print(*bstring)
I am trying to capitalize every other letter of a string which is given by and input. For some reason it give me the error 'string index out of range' and i have no idea why! the range is set from 0 to the length of the string so that cant be possible i thought!
s = input('Please enter a string: ')
p=s.lower()
o=s.upper()
q=p
k=len(s)
l=1
for x in range(0,k):
if l%2==0:
q=q[x].swapcase()
l+=1
else:
l+=1
print(q)
When you do this:
q=q[x].swapcase()
q becomes a single letter.
The next time around you try:
q[1]
but there is no q[1] because you made it a single letter.
This is one of several reasons why python encourages you to avoid creating index variables and instead looping over the items themselves. If you do that and give your variables more descriptive names, these kind of error are easier to catch. For example:
s = input('Please enter a string: ')
lower_case = s.lower()
new_string = ""
for index, letter in enumerate(lower_case):
if index % 2 == 0:
new_string += letter.swapcase()
else:
new_string += letter
print(new_string)