Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中连接字符串_Python_List_Join - Fatal编程技术网

在Python中连接字符串

在Python中连接字符串,python,list,join,Python,List,Join,此代码将名称打印为字符串,如何使用.join()来执行此操作,或者使用其他方法使输出为大写的名称中的单词,以及小写的和。 PS:对编程还是新手,很抱歉在问题的表述上有任何错误。如果没有引号或标点符号,你可以做如下操作 archive= ['Frederick the Great', 'Ivan the Terrible', 'maurice Of Nassau', 'Napoleon BONAPARTE'] n=[] n2

此代码将名称打印为字符串,如何使用
.join()
来执行此操作,或者使用其他方法使输出为大写的名称中的单词,以及小写的和。
PS:对编程还是新手,很抱歉在问题的表述上有任何错误。

如果没有引号或标点符号,你可以做如下操作

archive= ['Frederick the Great',
          'Ivan the Terrible',
          'maurice Of Nassau',
          'Napoleon BONAPARTE']

   n=[]
   n2=[]
   n3[]

    for line in archive:
        n.append(line)

    for x in n :
        lw = x.lower()
        for i in lw.split() :
            n2.append(i)

    for i in n2 :

        if i == 'of' or i == 'the' :
            i=i.lower()
            n3.append(i)

        else: 
            i=i.capitalize()
            n3.append(i) 

    print(n3)
另一个解决方案:

archive = ['Frederick the Great',
          'Ivan the Terrible',
          'maurice Of Nassau',
          'Napoleon BONAPARTE']

reformated = [
    ' '.join(word.capitalize()
             if word not in ('the', 'of')
             else word
             for word in line.lower().split())
    for line in archive
]

['Frederick the Great',
 'Ivan the Terrible',
 'Maurice of Nassau',
 'Napoleon Bonaparte']

此解决方案的优点是,它在一次放炮中降低了行,当单词if'of'或'The'时,它只会继续到下一个单词,这节省了处理周期。

我编写了一个短函数来将给定字符串大写。您可以使用
map
应用于列表中的所有字符串列表

archive= [
    'Frederick the Great',
    'Ivan the Terrible',
    'maurice Of Nassau',
    'Napoleon BONAPARTE'
]

lines = []
for line in archive:
    line = line.lower().split()
    for i, word in enumerate(line):
        if word in ('of', 'the'):
            continue
        line[i] = word.capitalize()
    lines.append(' '.join(line))

print lines

你期望的输出是什么?档案里到底有什么?现在可能是语法错误,您的存档部分没有引号或逗号。请确保在发布示例之前运行您的代码。n、n2和n3将导致错误,因为它们未初始化。例如,n=[]i thinnk i现在修复了语法错误输出应该是类似“腓特烈大帝”、“可怕的伊万”、“拿骚的莫里斯”之类的东西,“拿破仑·波拿巴”然而我得到了“伊万”,“恐怖”,“莫里斯”,“奥夫”,“拿骚”
archive= ['Frederick the Great',
          'Ivan the Terrible',
          'maurice Of Nassau',
          'Napoleon BONAPARTE']

def capitalize_phrase(text):
    s_capitalize = []
    for s in text.split(' '):
        if s.lower() in ['the', 'of']:
            s_capitalize.append(s.lower())
        else:
            s_capitalize.append(s.capitalize())
    return ' '.join(s_capitalize)

print(list(map(capitalize_phrase, archive)))