I’m trying to print all of the possible character substitutions for the word «otaku».
#!/usr/bin/python3
import itertools
user_input = "otaku"
dict = {
'c': ['c', 'C'],
'a': ['a', 'A', '@'],
't': ['t', 'T'],
'k': ['k', 'K'],
'u': ['u', 'U'],
'e': ['e', 'E', '3'],
'o': ['o', 'O', '0']
}
output = ""
for i in itertools.product(dict['o'],dict['t'],dict['a'],dict['k'],dict['u']):
output += ''.join(i) + "n"
print(output)
The above script works but I need the itertools.product() input (dict['o'],dict['t'],dict['a'],dict['k'],dict['u']) to be dynamic (e.g., new_list):
#!/usr/bin/python3
import itertools
user_input = "otaku"
dict = {
'c': ['c', 'C'],
'a': ['a', 'A', '@'],
't': ['t', 'T'],
'k': ['k', 'K'],
'u': ['u', 'U'],
'e': ['e', 'E', '3'],
'o': ['o', 'O', '0']
}
new_list = []
for i in user_input:
new_list.append(dict[i])
output = ""
for i in itertools.product(new_list):
output += ''.join(i) + "n"
print(output)
This errors with:
TypeError: sequence item 0: expected str instance, list found
I tried the solutions found here, but converting the list to a str breaks the itertools.product line.
How can I pass dynamic input into itertools.product()?
Desired output:
otaku
otakU
otaKu
otaKU
otAku
otAkU
otAKu
otAKU
ot@ku
ot@kU
ot@Ku
ot@KU
oTaku
oTakU
oTaKu
oTaKU
oTAku
oTAkU
oTAKu
oTAKU
oT@ku
oT@kU
oT@Ku
oT@KU
Otaku
OtakU
OtaKu
OtaKU
Ot@KU
The error “TypeError: sequence item 0: expected str instance, int found” happens when you try to join some numbers of type ‘int’ into a new string. The explanation of this guide will help you fix this error and other similar errors you may get in your code.
In Python, join() method joins all items in a collection as a list, a tuple,… to a string. Here is an example using the join() method to join all the strings in a list to a new string with commas separate.
device_list = ["smartphone", "tablet", "laptop", "desktop"] device_str = ','.join(device_list) print(device_str)
Output:
smartphone,tablet,laptop,desktop
Sometimes, you may want to join a list of integer numbers to a string, and you try to do the same as the example above, but your code does not work as you expected, and you get the error “TypeError: sequence item 0: expected str instance, int found”.
year_list = [2022, 2023, 2024, 2025] year_str = ','.join(year_list) print(year_str)
Output:
year_str = ','.join(year_list)
TypeError: sequence item 0: expected str instance, int found
How to solve the error?
Method 1: Use Python List Comprehension to create a new list of strings
This error occurs because the join() method requires the list has all of its elements of type ‘str’, not ‘int’. So, to fix this error, you can use the List Comprehension of Python to create a list of strings from the original list as this example.
year_list = [2022, 2023, 2024, 2025] year_str = ','.join([str(year) for year in year_list]) print(year_str)
Output:
2022,2023,2024,2025
Method 2: Use map() function
Another way to fix this error is to use the map() function, which applies a function to all elements of the list. In this case, the function you need to use with the map() function is the str() function to convert the element to a string.
year_list = [2022, 2023, 2024, 2025] year_str = ','.join(map(str, year_list)) print(year_str)
Output:
2022,2023,2024,2025
Example with a list of multiple datatypes
Both solutions above work not only with a list of integer numbers but also with a list of multiple datatypes.
exam_scores = [8, 8.25, "9.5"]
str1 = ','.join([str(s) for s in exam_scores])
str2 = ','.join(map(str, exam_scores))
print('str1: ' + str1)
print('str2: ' + str2)
Output:
str1: 8,8.25,9.5
str2: 8,8.25,9.5
As you can see, the results of both str1 and str2 are the same and work perfectly.
Summary
In this guide, I’ve showed you how to solve the error “TypeError: sequence item 0: expected str instance, int found” in Python. You can choose to use List Comprehension to create a new list of strings or use the map() function to solve the problem. Both solutions can also work perfectly with a list of multiple datatypes.
Maybe you are interested:
- TypeError: slice indices must be integers or None or have an __index__ method
- typeerror: string indices must be integers in python
- typeerror: takes 1 positional argument but 2 were given
- TypeError: unhashable type: ‘dict’

Hello, I’m Joseph Stanley. My major is IT and I want to share programming languages to you. If you have difficulty with JavaScript, TypeScript, C#, Python, C, C++, Java, let’s follow my articles. They are helpful for you.
Job: Developer
Name of the university: HUST
Major: IT
Programming Languages: JavaScript, TypeScript, C#, Python, C, C++, Java
|
zarar384 1 / 1 / 0 Регистрация: 04.06.2017 Сообщений: 73 |
||||
|
1 |
||||
|
10.05.2020, 23:05. Показов 6228. Ответов 4 Метки нет (Все метки)
Занимаюсь на Яндекс.Практикум и что-то завис на этой задачке. там, где знак (!) надо было дописать Жалуется: friends_string = ‘, ‘.join(user_friends)
__________________
0 |
|
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
10.05.2020, 23:05 |
|
4 |
|
1750 / 799 / 109 Регистрация: 29.01.2013 Сообщений: 4,836 |
|
|
10.05.2020, 23:09 |
2 |
|
zarar384, и что там надо дописать?
0 |
|
zarar384 1 / 1 / 0 Регистрация: 04.06.2017 Сообщений: 73 |
||||
|
10.05.2020, 23:11 [ТС] |
3 |
|||
|
Alli_Lupin, не,не. Эт я дописал. Вот сам код с заданием
0 |
|
1750 / 799 / 109 Регистрация: 29.01.2013 Сообщений: 4,836 |
|
|
10.05.2020, 23:15 |
4 |
|
Решениеzarar384, у вас в той строке, где ошибка, ожидается строковая переменная, а там — список. Приведите список к строке. Добавлено через 1 минуту
1 |
|
zarar384 1 / 1 / 0 Регистрация: 04.06.2017 Сообщений: 73 |
||||
|
11.05.2020, 00:18 [ТС] |
5 |
|||
|
Alli_Lupin, спасибо, чет сглупил Добавлено через 16 минут
0 |
|
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
11.05.2020, 00:18 |
|
Помогаю со студенческими работами здесь
TypeError: must be str, not bytes TypeError: must be str, not bytes Ошибка в коде: Traceback (most recent call last): TypeError: must be str, not int def convert_name(name): TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’
Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 5 |
Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Trying to understand what this error means. Does it mean it can’t parse the 0th list into a string?
What am I missing to make it turn those group members into a string? I have a join method but maybe it’s in the wrong place.
groups.py
musical_groups = [ ["Ad Rock", "MCA", "Mike D."], ["John Lennon", "Paul McCartney", "Ringo Starr", "George Harrison"], ["Salt", "Peppa", "Spinderella"], ["Rivers Cuomo", "Patrick Wilson", "Brian Bell", "Scott Shriner"], ["Chuck D.", "Flavor Flav", "Professor Griff", "Khari Winn", "DJ Lord"], ["Axl Rose", "Slash", "Duff McKagan", "Steven Adler"], ["Run", "DMC", "Jam Master Jay"], ] # Your code here group_members = ", ".join(musical_groups) for group in musical_groups: print(group_members)
1 Answer
seal-mask
PLUS
You are taking out each group and turning it into a string meaning when you loop over group_members you are in fact looping over characters and not elements in lists. You need to do something like this:
for group in musical_groups: print(", ".join(group))
import json
persones = []
def users_persone():
name = input('Введите имя контакта - ')
tel = input('Введите номер - ')
persone = {name: tel}
persones.append(persone)
MyFile = open('C:HPproverka.txt', 'w')
MyFile.writelines(persones)
MyFile.close()
with open('persones.json', 'w') as file:
json.dump(persones, file, ensure_ascii=False)
return persone
def main():
l = True
while l:
users_choise = input("Желаете ввести или получить контактные данные - ")
if users_choise == 'ввести':
users_persone()
elif users_choise == "получить":
print(MyFile)
users_choise_two = input("Желаете остановить програму - ")
if users_choise_two == 'да':
print("Програма закрыта")
l = False
main()
хочу что бы код сохранял номер и имя в текстовой файл но выдаёт ошибку
-
Вопрос заданболее года назад
-
435 просмотров
MyFile = open(‘C:HPproverka.txt’, ‘w’)
MyFile.writelines(persones)
MyFile.close()
writelines() ожидает получить на вход массив СТРОК, а ты даёшь массив словарей. Отсюда и ошибка.
Зачем ты вообще этот фрагмент написал, если чуть дальше у тебя нормальное сохранение в json?
Пригласить эксперта
-
Показать ещё
Загружается…
29 янв. 2023, в 03:07
300000 руб./за проект
29 янв. 2023, в 02:16
700000 руб./за проект
29 янв. 2023, в 01:54
5000 руб./за проект
Минуточку внимания
Hi,
I have the same problem.
You can see my debug
[Phpcs] php -l -d display_errors=On /Users/julien/Sites/www/project/application/frontend/controllers/access.php
[Phpcs] php -l -d display_errors=On /Users/julien/Sites/www/project/application/frontend/controllers/access.php
[Phpcs] cwd: /Users/julien
[Phpcs] No syntax errors detected in /Users/julien/Sites/www/project/application/frontend/controllers/access.php
[Phpcs] phpcs —report=checkstyle —standard=PSR2 -n /Users/julien/Sites/www/project/application/frontend/controllers/access.php
[Phpcs] phpcs —report=checkstyle —standard=PSR2 -n /Users/julien/Sites/www/project/application/frontend/controllers/access.php
[Phpcs] cwd: /Users/julien
Traceback (most recent call last):
File «/Applications/Sublime Text.app/Contents/MacOS/sublime_plugin.py», line 556, in run_
return self.run(edit)
File «phpcs in /Users/julien/Library/Application Support/Sublime Text 3/Installed Packages/Phpcs.sublime-package», line 649, in run
File «phpcs in /Users/julien/Library/Application Support/Sublime Text 3/Installed Packages/Phpcs.sublime-package», line 467, in run
File «phpcs in /Users/julien/Library/Application Support/Sublime Text 3/Installed Packages/Phpcs.sublime-package», line 143, in get_errors
File «phpcs in /Users/julien/Library/Application Support/Sublime Text 3/Installed Packages/Phpcs.sublime-package», line 219, in execute
File «phpcs in /Users/julien/Library/Application Support/Sublime Text 3/Installed Packages/Phpcs.sublime-package», line 222, in parse_report
File «phpcs in /Users/julien/Library/Application Support/Sublime Text 3/Installed Packages/Phpcs.sublime-package», line 173, in shell_out
File «./subprocess.py», line 824, in init
File «./subprocess.py», line 1448, in _execute_child
FileNotFoundError: [Errno 2] No such file or directory: ‘phpcs’
When I execute the command (phpcs —report=checkstyle —standard=PSR2 -n /Users/julien/Sites/www/project/application/frontend/controllers/access.php) in a terminal, I have no problem and I get the error list.
My sublime config file
{
«auto_complete»: true,
«bold_folder_labels»: true,
«color_scheme»: «Packages/Color Scheme — Default/Monokai Bright.tmTheme»,
«draw_minimap_border»: false,
«extensions_to_blacklist»:
[
],
«extensions_to_execute»:
[
«php»,
«inc»
],
«find_selected_text»: false,
«font_size»: 16,
«gutter»: true,
«highlight_line»: true,
«ignored_packages»:
[
«Vintage»
],
«line_padding_bottom»: 1,
«match_brackets»: true,
«match_brackets_angle»: false,
«match_brackets_braces»: true,
«match_brackets_content»: true,
«match_brackets_square»: true,
«php_cs_fixer_additional_args»:
{
},
«php_cs_fixer_executable_path»: «/usr/local/php5/bin/php-cs-fixer»,
«php_cs_fixer_on_save»: false,
«php_cs_fixer_show_quick_panel»: true,
«phpcbf_additional_args»:
{
«—standard»: «PSR2»,
«-n»: «»
},
«phpcbf_executable_path»: «/usr/local/php5/bin/phpcbf»,
«phpcbf_on_save»: false,
«phpcbf_show_quick_panel»: true,
«phpcs_additional_args»:
{
«—standard»: «PSR2»,
«-n»: «»
},
«phpcs_command_on_save»: false,
«phpcs_executable_path»: «/usr/local/php5/bin/phpcs»,
«phpcs_execute_on_save»: false,
«phpcs_icon_scope_color»: «comment»,
«phpcs_linter_command_on_save»: false,
«phpcs_linter_regex»: «(?P.*) on line (?Pd+)»,
«phpcs_linter_run»: true,
«phpcs_outline_for_errors»: true,
«phpcs_php_path»: «/usr/local/php5/bin/php»,
«phpcs_show_errors_in_status»: true,
«phpcs_show_errors_on_save»: true,
«phpcs_show_gutter_marks»: true,
«phpcs_show_quick_panel»: true,
«phpcs_sniffer_run»: true,
«phpmd_additional_args»:
{
«codesize,unusedcode,naming»: «»
},
«phpmd_command_on_save»: false,
«phpmd_executable_path»: «/usr/local/php5/bin/phpmd»,
«phpmd_run»: true,
«save_on_focus_lost»: true,
«scheck_additional_args»:
{
«-strict»: «»
},
«scheck_command_on_save»: false,
«scheck_executable_path»: «»,
«scheck_run»: false,
«scroll_past_end»: true,
«show_debug»: false,
«tab_size»: 4,
«translate_tabs_to_spaces»: true
}
Is there a config error ?
Thanks.
Сообщение было отмечено zarar384 как решение